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 "net/third_party/quiche/src/quic/core/quic_session.h"
6 
7 #include <cstdint>
8 #include <set>
9 #include <string>
10 #include <utility>
11 
12 #include "absl/base/macros.h"
13 #include "absl/strings/string_view.h"
14 #include "absl/types/optional.h"
15 #include "net/third_party/quiche/src/quic/core/crypto/crypto_protocol.h"
16 #include "net/third_party/quiche/src/quic/core/crypto/null_decrypter.h"
17 #include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
18 #include "net/third_party/quiche/src/quic/core/crypto/transport_parameters.h"
19 #include "net/third_party/quiche/src/quic/core/frames/quic_max_streams_frame.h"
20 #include "net/third_party/quiche/src/quic/core/quic_crypto_stream.h"
21 #include "net/third_party/quiche/src/quic/core/quic_data_writer.h"
22 #include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
23 #include "net/third_party/quiche/src/quic/core/quic_packets.h"
24 #include "net/third_party/quiche/src/quic/core/quic_stream.h"
25 #include "net/third_party/quiche/src/quic/core/quic_utils.h"
26 #include "net/third_party/quiche/src/quic/core/quic_versions.h"
27 #include "net/third_party/quiche/src/quic/platform/api/quic_expect_bug.h"
28 #include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
29 #include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h"
30 #include "net/third_party/quiche/src/quic/platform/api/quic_mem_slice_storage.h"
31 #include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h"
32 #include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
33 #include "net/third_party/quiche/src/quic/platform/api/quic_test_mem_slice_vector.h"
34 #include "net/third_party/quiche/src/quic/test_tools/mock_quic_session_visitor.h"
35 #include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
36 #include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
37 #include "net/third_party/quiche/src/quic/test_tools/quic_flow_controller_peer.h"
38 #include "net/third_party/quiche/src/quic/test_tools/quic_session_peer.h"
39 #include "net/third_party/quiche/src/quic/test_tools/quic_stream_id_manager_peer.h"
40 #include "net/third_party/quiche/src/quic/test_tools/quic_stream_peer.h"
41 #include "net/third_party/quiche/src/quic/test_tools/quic_stream_send_buffer_peer.h"
42 #include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
43 #include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h"
44 
45 using spdy::kV3HighestPriority;
46 using spdy::SpdyPriority;
47 using ::testing::_;
48 using ::testing::AnyNumber;
49 using ::testing::AtLeast;
50 using ::testing::InSequence;
51 using ::testing::Invoke;
52 using ::testing::NiceMock;
53 using ::testing::Return;
54 using ::testing::StrictMock;
55 using ::testing::WithArg;
56 
57 namespace quic {
58 namespace test {
59 namespace {
60 
61 class TestCryptoStream : public QuicCryptoStream, public QuicCryptoHandshaker {
62  public:
TestCryptoStream(QuicSession * session)63   explicit TestCryptoStream(QuicSession* session)
64       : QuicCryptoStream(session),
65         QuicCryptoHandshaker(this, session),
66         encryption_established_(false),
67         one_rtt_keys_available_(false),
68         params_(new QuicCryptoNegotiatedParameters) {
69     // Simulate a negotiated cipher_suite with a fake value.
70     params_->cipher_suite = 1;
71   }
72 
EstablishZeroRttEncryption()73   void EstablishZeroRttEncryption() {
74     encryption_established_ = true;
75     session()->connection()->SetEncrypter(
76         ENCRYPTION_ZERO_RTT,
77         std::make_unique<NullEncrypter>(session()->perspective()));
78   }
79 
OnHandshakeMessage(const CryptoHandshakeMessage &)80   void OnHandshakeMessage(const CryptoHandshakeMessage& /*message*/) override {
81     encryption_established_ = true;
82     one_rtt_keys_available_ = true;
83     QuicErrorCode error;
84     std::string error_details;
85     session()->config()->SetInitialStreamFlowControlWindowToSend(
86         kInitialStreamFlowControlWindowForTest);
87     session()->config()->SetInitialSessionFlowControlWindowToSend(
88         kInitialSessionFlowControlWindowForTest);
89     if (session()->version().AuthenticatesHandshakeConnectionIds()) {
90       if (session()->perspective() == Perspective::IS_CLIENT) {
91         session()->config()->SetOriginalConnectionIdToSend(
92             session()->connection()->connection_id());
93         session()->config()->SetInitialSourceConnectionIdToSend(
94             session()->connection()->connection_id());
95       } else {
96         session()->config()->SetInitialSourceConnectionIdToSend(
97             session()->connection()->client_connection_id());
98       }
99     }
100     if (session()->connection()->version().handshake_protocol ==
101         PROTOCOL_TLS1_3) {
102       TransportParameters transport_parameters;
103       EXPECT_TRUE(
104           session()->config()->FillTransportParameters(&transport_parameters));
105       error = session()->config()->ProcessTransportParameters(
106           transport_parameters, /* is_resumption = */ false, &error_details);
107     } else {
108       CryptoHandshakeMessage msg;
109       session()->config()->ToHandshakeMessage(&msg, transport_version());
110       error =
111           session()->config()->ProcessPeerHello(msg, CLIENT, &error_details);
112     }
113     EXPECT_THAT(error, IsQuicNoError());
114     session()->OnNewEncryptionKeyAvailable(
115         ENCRYPTION_FORWARD_SECURE,
116         std::make_unique<NullEncrypter>(session()->perspective()));
117     session()->OnConfigNegotiated();
118     if (session()->connection()->version().handshake_protocol ==
119         PROTOCOL_TLS1_3) {
120       session()->OnTlsHandshakeComplete();
121     } else {
122       session()->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
123     }
124     session()->DiscardOldEncryptionKey(ENCRYPTION_INITIAL);
125   }
126 
127   // QuicCryptoStream implementation
EarlyDataReason() const128   ssl_early_data_reason_t EarlyDataReason() const override {
129     return ssl_early_data_unknown;
130   }
encryption_established() const131   bool encryption_established() const override {
132     return encryption_established_;
133   }
one_rtt_keys_available() const134   bool one_rtt_keys_available() const override {
135     return one_rtt_keys_available_;
136   }
crypto_negotiated_params() const137   const QuicCryptoNegotiatedParameters& crypto_negotiated_params()
138       const override {
139     return *params_;
140   }
crypto_message_parser()141   CryptoMessageParser* crypto_message_parser() override {
142     return QuicCryptoHandshaker::crypto_message_parser();
143   }
OnPacketDecrypted(EncryptionLevel)144   void OnPacketDecrypted(EncryptionLevel /*level*/) override {}
OnOneRttPacketAcknowledged()145   void OnOneRttPacketAcknowledged() override {}
OnHandshakePacketSent()146   void OnHandshakePacketSent() override {}
OnHandshakeDoneReceived()147   void OnHandshakeDoneReceived() override {}
GetHandshakeState() const148   HandshakeState GetHandshakeState() const override {
149     return one_rtt_keys_available() ? HANDSHAKE_COMPLETE : HANDSHAKE_START;
150   }
SetServerApplicationStateForResumption(std::unique_ptr<ApplicationState>)151   void SetServerApplicationStateForResumption(
152       std::unique_ptr<ApplicationState> /*application_state*/) override {}
153   MOCK_METHOD(bool, KeyUpdateSupportedLocally, (), (const, override));
154   MOCK_METHOD(std::unique_ptr<QuicDecrypter>,
155               AdvanceKeysAndCreateCurrentOneRttDecrypter,
156               (),
157               (override));
158   MOCK_METHOD(std::unique_ptr<QuicEncrypter>,
159               CreateCurrentOneRttEncrypter,
160               (),
161               (override));
162 
163   MOCK_METHOD(void, OnCanWrite, (), (override));
HasPendingCryptoRetransmission() const164   bool HasPendingCryptoRetransmission() const override { return false; }
165 
166   MOCK_METHOD(bool, HasPendingRetransmission, (), (const, override));
167 
OnConnectionClosed(QuicErrorCode,ConnectionCloseSource)168   void OnConnectionClosed(QuicErrorCode /*error*/,
169                           ConnectionCloseSource /*source*/) override {}
170 
171  private:
172   using QuicCryptoStream::session;
173 
174   bool encryption_established_;
175   bool one_rtt_keys_available_;
176   QuicReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_;
177 };
178 
179 class TestStream : public QuicStream {
180  public:
TestStream(QuicStreamId id,QuicSession * session,StreamType type)181   TestStream(QuicStreamId id, QuicSession* session, StreamType type)
182       : TestStream(id, session, /*is_static=*/false, type) {}
183 
TestStream(QuicStreamId id,QuicSession * session,bool is_static,StreamType type)184   TestStream(QuicStreamId id,
185              QuicSession* session,
186              bool is_static,
187              StreamType type)
188       : QuicStream(id, session, is_static, type) {}
189 
TestStream(PendingStream * pending,QuicSession * session,StreamType type)190   TestStream(PendingStream* pending, QuicSession* session, StreamType type)
191       : QuicStream(pending, session, type, /*is_static=*/false) {}
192 
193   using QuicStream::CloseWriteSide;
194   using QuicStream::WriteMemSlices;
195 
OnDataAvailable()196   void OnDataAvailable() override {}
197 
198   MOCK_METHOD(void, OnCanWrite, (), (override));
199   MOCK_METHOD(bool,
200               RetransmitStreamData,
201               (QuicStreamOffset, QuicByteCount, bool, TransmissionType),
202               (override));
203 
204   MOCK_METHOD(bool, HasPendingRetransmission, (), (const, override));
205 };
206 
207 class TestSession : public QuicSession {
208  public:
TestSession(QuicConnection * connection,MockQuicSessionVisitor * session_visitor)209   explicit TestSession(QuicConnection* connection,
210                        MockQuicSessionVisitor* session_visitor)
211       : QuicSession(connection,
212                     session_visitor,
213                     DefaultQuicConfig(),
214                     CurrentSupportedVersions(),
215                     /*num_expected_unidirectional_static_streams = */ 0),
216         crypto_stream_(this),
217         writev_consumes_all_data_(false),
218         uses_pending_streams_(false),
219         num_incoming_streams_created_(0) {
220     EXPECT_CALL(*GetMutableCryptoStream(), KeyUpdateSupportedLocally())
221         .WillRepeatedly(Return(false));
222     Initialize();
223     this->connection()->SetEncrypter(
224         ENCRYPTION_FORWARD_SECURE,
225         std::make_unique<NullEncrypter>(connection->perspective()));
226     if (this->connection()->version().SupportsAntiAmplificationLimit()) {
227       QuicConnectionPeer::SetAddressValidated(this->connection());
228     }
229   }
230 
~TestSession()231   ~TestSession() override { DeleteConnection(); }
232 
GetMutableCryptoStream()233   TestCryptoStream* GetMutableCryptoStream() override {
234     return &crypto_stream_;
235   }
236 
GetCryptoStream() const237   const TestCryptoStream* GetCryptoStream() const override {
238     return &crypto_stream_;
239   }
240 
CreateOutgoingBidirectionalStream()241   TestStream* CreateOutgoingBidirectionalStream() {
242     QuicStreamId id = GetNextOutgoingBidirectionalStreamId();
243     if (id ==
244         QuicUtils::GetInvalidStreamId(connection()->transport_version())) {
245       return nullptr;
246     }
247     TestStream* stream = new TestStream(id, this, BIDIRECTIONAL);
248     ActivateStream(QuicWrapUnique(stream));
249     return stream;
250   }
251 
CreateOutgoingUnidirectionalStream()252   TestStream* CreateOutgoingUnidirectionalStream() {
253     TestStream* stream = new TestStream(GetNextOutgoingUnidirectionalStreamId(),
254                                         this, WRITE_UNIDIRECTIONAL);
255     ActivateStream(QuicWrapUnique(stream));
256     return stream;
257   }
258 
CreateIncomingStream(QuicStreamId id)259   TestStream* CreateIncomingStream(QuicStreamId id) override {
260     // Enforce the limit on the number of open streams.
261     if (!VersionHasIetfQuicFrames(connection()->transport_version()) &&
262         stream_id_manager().num_open_incoming_streams() + 1 >
263             max_open_incoming_bidirectional_streams()) {
264       // No need to do this test for version 99; it's done by
265       // QuicSession::GetOrCreateStream.
266       connection()->CloseConnection(
267           QUIC_TOO_MANY_OPEN_STREAMS, "Too many streams!",
268           ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
269       return nullptr;
270     }
271 
272     TestStream* stream = new TestStream(
273         id, this,
274         DetermineStreamType(id, connection()->version(), perspective(),
275                             /*is_incoming=*/true, BIDIRECTIONAL));
276     ActivateStream(QuicWrapUnique(stream));
277     ++num_incoming_streams_created_;
278     return stream;
279   }
280 
CreateIncomingStream(PendingStream * pending)281   TestStream* CreateIncomingStream(PendingStream* pending) override {
282     QuicStreamId id = pending->id();
283     TestStream* stream = new TestStream(
284         pending, this,
285         DetermineStreamType(id, connection()->version(), perspective(),
286                             /*is_incoming=*/true, BIDIRECTIONAL));
287     ActivateStream(QuicWrapUnique(stream));
288     ++num_incoming_streams_created_;
289     return stream;
290   }
291 
292   // QuicSession doesn't do anything in this method. So it's overridden here to
293   // test that the session handles pending streams correctly in terms of
294   // receiving stream frames.
ProcessPendingStream(PendingStream * pending)295   bool ProcessPendingStream(PendingStream* pending) override {
296     struct iovec iov;
297     if (pending->sequencer()->GetReadableRegion(&iov)) {
298       // Create TestStream once the first byte is received.
299       CreateIncomingStream(pending);
300       return true;
301     }
302     return false;
303   }
304 
IsClosedStream(QuicStreamId id)305   bool IsClosedStream(QuicStreamId id) {
306     return QuicSession::IsClosedStream(id);
307   }
308 
GetOrCreateStream(QuicStreamId stream_id)309   QuicStream* GetOrCreateStream(QuicStreamId stream_id) {
310     return QuicSession::GetOrCreateStream(stream_id);
311   }
312 
ShouldKeepConnectionAlive() const313   bool ShouldKeepConnectionAlive() const override {
314     return GetNumActiveStreams() > 0;
315   }
316 
WritevData(QuicStreamId id,size_t write_length,QuicStreamOffset offset,StreamSendingState state,TransmissionType type,absl::optional<EncryptionLevel> level)317   QuicConsumedData WritevData(QuicStreamId id,
318                               size_t write_length,
319                               QuicStreamOffset offset,
320                               StreamSendingState state,
321                               TransmissionType type,
322                               absl::optional<EncryptionLevel> level) override {
323     bool fin = state != NO_FIN;
324     QuicConsumedData consumed(write_length, fin);
325     if (!writev_consumes_all_data_) {
326       consumed =
327           QuicSession::WritevData(id, write_length, offset, state, type, level);
328     }
329     QuicSessionPeer::GetWriteBlockedStreams(this)->UpdateBytesForStream(
330         id, consumed.bytes_consumed);
331     return consumed;
332   }
333 
334   MOCK_METHOD(void,
335               OnCanCreateNewOutgoingStream,
336               (bool unidirectional),
337               (override));
338 
set_writev_consumes_all_data(bool val)339   void set_writev_consumes_all_data(bool val) {
340     writev_consumes_all_data_ = val;
341   }
342 
SendStreamData(QuicStream * stream)343   QuicConsumedData SendStreamData(QuicStream* stream) {
344     struct iovec iov;
345     if (!QuicUtils::IsCryptoStreamId(connection()->transport_version(),
346                                      stream->id()) &&
347         this->connection()->encryption_level() != ENCRYPTION_FORWARD_SECURE) {
348       this->connection()->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
349     }
350     MakeIOVector("not empty", &iov);
351     QuicStreamPeer::SendBuffer(stream).SaveStreamData(&iov, 1, 0, 9);
352     QuicConsumedData consumed =
353         WritevData(stream->id(), 9, 0, FIN, NOT_RETRANSMISSION,
354                    GetEncryptionLevelToSendApplicationData());
355     QuicStreamPeer::SendBuffer(stream).OnStreamDataConsumed(
356         consumed.bytes_consumed);
357     return consumed;
358   }
359 
save_frame()360   const QuicFrame& save_frame() { return save_frame_; }
361 
SaveFrame(const QuicFrame & frame)362   bool SaveFrame(const QuicFrame& frame) {
363     save_frame_ = frame;
364     DeleteFrame(&const_cast<QuicFrame&>(frame));
365     return true;
366   }
367 
SendLargeFakeData(QuicStream * stream,int bytes)368   QuicConsumedData SendLargeFakeData(QuicStream* stream, int bytes) {
369     DCHECK(writev_consumes_all_data_);
370     return WritevData(stream->id(), bytes, 0, FIN, NOT_RETRANSMISSION,
371                       GetEncryptionLevelToSendApplicationData());
372   }
373 
UsesPendingStreams() const374   bool UsesPendingStreams() const override { return uses_pending_streams_; }
375 
set_uses_pending_streams(bool uses_pending_streams)376   void set_uses_pending_streams(bool uses_pending_streams) {
377     uses_pending_streams_ = uses_pending_streams;
378   }
379 
num_incoming_streams_created() const380   int num_incoming_streams_created() const {
381     return num_incoming_streams_created_;
382   }
383 
384   using QuicSession::ActivateStream;
385   using QuicSession::CanOpenNextOutgoingBidirectionalStream;
386   using QuicSession::CanOpenNextOutgoingUnidirectionalStream;
387   using QuicSession::closed_streams;
388   using QuicSession::GetNextOutgoingBidirectionalStreamId;
389   using QuicSession::GetNextOutgoingUnidirectionalStreamId;
390   using QuicSession::stream_map;
391 
392  private:
393   StrictMock<TestCryptoStream> crypto_stream_;
394 
395   bool writev_consumes_all_data_;
396   bool uses_pending_streams_;
397   QuicFrame save_frame_;
398   int num_incoming_streams_created_;
399 };
400 
401 class QuicSessionTestBase : public QuicTestWithParam<ParsedQuicVersion> {
402  protected:
QuicSessionTestBase(Perspective perspective,bool configure_session)403   QuicSessionTestBase(Perspective perspective, bool configure_session)
404       : connection_(
405             new StrictMock<MockQuicConnection>(&helper_,
406                                                &alarm_factory_,
407                                                perspective,
408                                                SupportedVersions(GetParam()))),
409         session_(connection_, &session_visitor_),
410         configure_session_(configure_session) {
411     session_.config()->SetInitialStreamFlowControlWindowToSend(
412         kInitialStreamFlowControlWindowForTest);
413     session_.config()->SetInitialSessionFlowControlWindowToSend(
414         kInitialSessionFlowControlWindowForTest);
415 
416     if (configure_session) {
417       if (VersionHasIetfQuicFrames(transport_version())) {
418         EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1);
419         EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(true)).Times(1);
420       }
421       QuicConfigPeer::SetReceivedMaxBidirectionalStreams(
422           session_.config(), kDefaultMaxStreamsPerConnection);
423       QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(
424           session_.config(), kDefaultMaxStreamsPerConnection);
425       QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional(
426           session_.config(), kMinimumFlowControlSendWindow);
427       QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesIncomingBidirectional(
428           session_.config(), kMinimumFlowControlSendWindow);
429       QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional(
430           session_.config(), kMinimumFlowControlSendWindow);
431       QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(
432           session_.config(), kMinimumFlowControlSendWindow);
433       connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
434       session_.OnConfigNegotiated();
435     }
436     TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
437     EXPECT_CALL(*crypto_stream, HasPendingRetransmission())
438         .Times(testing::AnyNumber());
439     testing::Mock::VerifyAndClearExpectations(&session_);
440   }
441 
~QuicSessionTestBase()442   ~QuicSessionTestBase() {
443     if (configure_session_) {
444       EXPECT_TRUE(session_.is_configured());
445     }
446   }
447 
CheckClosedStreams()448   void CheckClosedStreams() {
449     QuicStreamId first_stream_id = QuicUtils::GetFirstBidirectionalStreamId(
450         connection_->transport_version(), Perspective::IS_CLIENT);
451     if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
452       first_stream_id =
453           QuicUtils::GetCryptoStreamId(connection_->transport_version());
454     }
455     for (QuicStreamId i = first_stream_id; i < 100; i++) {
456       if (!QuicContainsKey(closed_streams_, i)) {
457         EXPECT_FALSE(session_.IsClosedStream(i)) << " stream id: " << i;
458       } else {
459         EXPECT_TRUE(session_.IsClosedStream(i)) << " stream id: " << i;
460       }
461     }
462   }
463 
CloseStream(QuicStreamId id)464   void CloseStream(QuicStreamId id) {
465     if (VersionHasIetfQuicFrames(transport_version())) {
466       if (QuicUtils::GetStreamType(
467               id, session_.perspective(), session_.IsIncomingStream(id),
468               connection_->version()) == READ_UNIDIRECTIONAL) {
469         // Verify STOP_SENDING but no RESET_STREAM is sent for
470         // READ_UNIDIRECTIONAL streams.
471         EXPECT_CALL(*connection_, SendControlFrame(_))
472             .Times(1)
473             .WillOnce(Invoke(&ClearControlFrame));
474         EXPECT_CALL(*connection_, OnStreamReset(id, _)).Times(1);
475       } else if (QuicUtils::GetStreamType(
476                      id, session_.perspective(), session_.IsIncomingStream(id),
477                      connection_->version()) == WRITE_UNIDIRECTIONAL) {
478         // Verify RESET_STREAM but not STOP_SENDING is sent for write-only
479         // stream.
480         EXPECT_CALL(*connection_, SendControlFrame(_))
481             .Times(1)
482             .WillOnce(Invoke(&ClearControlFrame));
483         EXPECT_CALL(*connection_, OnStreamReset(id, _));
484       } else {
485         // Verify RESET_STREAM and STOP_SENDING are sent for BIDIRECTIONAL
486         // streams.
487         EXPECT_CALL(*connection_, SendControlFrame(_))
488             .Times(2)
489             .WillRepeatedly(Invoke(&ClearControlFrame));
490         EXPECT_CALL(*connection_, OnStreamReset(id, _));
491       }
492     } else {
493       EXPECT_CALL(*connection_, SendControlFrame(_))
494           .WillOnce(Invoke(&ClearControlFrame));
495       EXPECT_CALL(*connection_, OnStreamReset(id, _));
496     }
497     session_.ResetStream(id, QUIC_STREAM_CANCELLED);
498     closed_streams_.insert(id);
499   }
500 
CompleteHandshake()501   void CompleteHandshake() {
502     CryptoHandshakeMessage msg;
503     if (connection_->version().HasHandshakeDone() &&
504         connection_->perspective() == Perspective::IS_SERVER) {
505       EXPECT_CALL(*connection_, SendControlFrame(_))
506           .WillOnce(Invoke(&ClearControlFrame));
507     }
508     session_.GetMutableCryptoStream()->OnHandshakeMessage(msg);
509   }
510 
transport_version() const511   QuicTransportVersion transport_version() const {
512     return connection_->transport_version();
513   }
514 
GetNthClientInitiatedBidirectionalId(int n)515   QuicStreamId GetNthClientInitiatedBidirectionalId(int n) {
516     return QuicUtils::GetFirstBidirectionalStreamId(
517                connection_->transport_version(), Perspective::IS_CLIENT) +
518            QuicUtils::StreamIdDelta(connection_->transport_version()) * n;
519   }
520 
GetNthClientInitiatedUnidirectionalId(int n)521   QuicStreamId GetNthClientInitiatedUnidirectionalId(int n) {
522     return QuicUtils::GetFirstUnidirectionalStreamId(
523                connection_->transport_version(), Perspective::IS_CLIENT) +
524            QuicUtils::StreamIdDelta(connection_->transport_version()) * n;
525   }
526 
GetNthServerInitiatedBidirectionalId(int n)527   QuicStreamId GetNthServerInitiatedBidirectionalId(int n) {
528     return QuicUtils::GetFirstBidirectionalStreamId(
529                connection_->transport_version(), Perspective::IS_SERVER) +
530            QuicUtils::StreamIdDelta(connection_->transport_version()) * n;
531   }
532 
GetNthServerInitiatedUnidirectionalId(int n)533   QuicStreamId GetNthServerInitiatedUnidirectionalId(int n) {
534     return QuicUtils::GetFirstUnidirectionalStreamId(
535                connection_->transport_version(), Perspective::IS_SERVER) +
536            QuicUtils::StreamIdDelta(connection_->transport_version()) * n;
537   }
538 
StreamCountToId(QuicStreamCount stream_count,Perspective perspective,bool bidirectional)539   QuicStreamId StreamCountToId(QuicStreamCount stream_count,
540                                Perspective perspective,
541                                bool bidirectional) {
542     // Calculate and build up stream ID rather than use
543     // GetFirst... because tests that rely on this method
544     // needs to do the stream count where #1 is 0/1/2/3, and not
545     // take into account that stream 0 is special.
546     QuicStreamId id =
547         ((stream_count - 1) * QuicUtils::StreamIdDelta(transport_version()));
548     if (!bidirectional) {
549       id |= 0x2;
550     }
551     if (perspective == Perspective::IS_SERVER) {
552       id |= 0x1;
553     }
554     return id;
555   }
556 
557   MockQuicConnectionHelper helper_;
558   MockAlarmFactory alarm_factory_;
559   NiceMock<MockQuicSessionVisitor> session_visitor_;
560   StrictMock<MockQuicConnection>* connection_;
561   TestSession session_;
562   std::set<QuicStreamId> closed_streams_;
563   bool configure_session_;
564 };
565 
566 class QuicSessionTestServer : public QuicSessionTestBase {
567  public:
568   // CheckMultiPathResponse validates that a written packet
569   // contains both expected path responses.
CheckMultiPathResponse(const char * buffer,size_t buf_len,const QuicIpAddress &,const QuicSocketAddress &,PerPacketOptions *)570   WriteResult CheckMultiPathResponse(const char* buffer,
571                                      size_t buf_len,
572                                      const QuicIpAddress& /*self_address*/,
573                                      const QuicSocketAddress& /*peer_address*/,
574                                      PerPacketOptions* /*options*/) {
575     QuicEncryptedPacket packet(buffer, buf_len);
576     {
577       InSequence s;
578       EXPECT_CALL(framer_visitor_, OnPacket());
579       EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_));
580       EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_));
581       EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_));
582       EXPECT_CALL(framer_visitor_, OnPacketHeader(_));
583       EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_))
584           .WillOnce(
585               WithArg<0>(Invoke([this](const QuicPathResponseFrame& frame) {
586                 EXPECT_EQ(path_frame_buffer1_, frame.data_buffer);
587                 return true;
588               })));
589       EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_))
590           .WillOnce(
591               WithArg<0>(Invoke([this](const QuicPathResponseFrame& frame) {
592                 EXPECT_EQ(path_frame_buffer2_, frame.data_buffer);
593                 return true;
594               })));
595       EXPECT_CALL(framer_visitor_, OnPacketComplete());
596     }
597     client_framer_.ProcessPacket(packet);
598     return WriteResult(WRITE_STATUS_OK, 0);
599   }
600 
601  protected:
QuicSessionTestServer()602   QuicSessionTestServer()
603       : QuicSessionTestBase(Perspective::IS_SERVER, /*configure_session=*/true),
604         path_frame_buffer1_({0, 1, 2, 3, 4, 5, 6, 7}),
605         path_frame_buffer2_({8, 9, 10, 11, 12, 13, 14, 15}),
606         client_framer_(SupportedVersions(GetParam()),
607                        QuicTime::Zero(),
608                        Perspective::IS_CLIENT,
609                        kQuicDefaultConnectionIdLength) {
610     client_framer_.set_visitor(&framer_visitor_);
611     client_framer_.SetInitialObfuscators(TestConnectionId());
612     if (client_framer_.version().KnowsWhichDecrypterToUse()) {
613       client_framer_.InstallDecrypter(
614           ENCRYPTION_FORWARD_SECURE,
615           std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
616     }
617   }
618 
619   QuicPathFrameBuffer path_frame_buffer1_;
620   QuicPathFrameBuffer path_frame_buffer2_;
621   StrictMock<MockFramerVisitor> framer_visitor_;
622   // Framer used to process packets sent by server.
623   QuicFramer client_framer_;
624 };
625 
626 INSTANTIATE_TEST_SUITE_P(Tests,
627                          QuicSessionTestServer,
628                          ::testing::ValuesIn(AllSupportedVersions()),
629                          ::testing::PrintToStringParamName());
630 
TEST_P(QuicSessionTestServer,PeerAddress)631 TEST_P(QuicSessionTestServer, PeerAddress) {
632   EXPECT_EQ(QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort),
633             session_.peer_address());
634 }
635 
TEST_P(QuicSessionTestServer,SelfAddress)636 TEST_P(QuicSessionTestServer, SelfAddress) {
637   EXPECT_TRUE(session_.self_address().IsInitialized());
638 }
639 
TEST_P(QuicSessionTestServer,DontCallOnWriteBlockedForDisconnectedConnection)640 TEST_P(QuicSessionTestServer, DontCallOnWriteBlockedForDisconnectedConnection) {
641   EXPECT_CALL(*connection_, CloseConnection(_, _, _))
642       .WillOnce(
643           Invoke(connection_, &MockQuicConnection::ReallyCloseConnection));
644   connection_->CloseConnection(QUIC_NO_ERROR, "Everything is fine.",
645                                ConnectionCloseBehavior::SILENT_CLOSE);
646   ASSERT_FALSE(connection_->connected());
647 
648   EXPECT_CALL(session_visitor_, OnWriteBlocked(_)).Times(0);
649   session_.OnWriteBlocked();
650 }
651 
TEST_P(QuicSessionTestServer,OneRttKeysAvailable)652 TEST_P(QuicSessionTestServer, OneRttKeysAvailable) {
653   EXPECT_FALSE(session_.OneRttKeysAvailable());
654   CompleteHandshake();
655   EXPECT_TRUE(session_.OneRttKeysAvailable());
656 }
657 
TEST_P(QuicSessionTestServer,IsClosedStreamDefault)658 TEST_P(QuicSessionTestServer, IsClosedStreamDefault) {
659   // Ensure that no streams are initially closed.
660   QuicStreamId first_stream_id = QuicUtils::GetFirstBidirectionalStreamId(
661       connection_->transport_version(), Perspective::IS_CLIENT);
662   if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
663     first_stream_id =
664         QuicUtils::GetCryptoStreamId(connection_->transport_version());
665   }
666   for (QuicStreamId i = first_stream_id; i < 100; i++) {
667     EXPECT_FALSE(session_.IsClosedStream(i)) << "stream id: " << i;
668   }
669 }
670 
TEST_P(QuicSessionTestServer,AvailableBidirectionalStreams)671 TEST_P(QuicSessionTestServer, AvailableBidirectionalStreams) {
672   ASSERT_TRUE(session_.GetOrCreateStream(
673                   GetNthClientInitiatedBidirectionalId(3)) != nullptr);
674   // Smaller bidirectional streams should be available.
675   EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
676       &session_, GetNthClientInitiatedBidirectionalId(1)));
677   EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
678       &session_, GetNthClientInitiatedBidirectionalId(2)));
679   ASSERT_TRUE(session_.GetOrCreateStream(
680                   GetNthClientInitiatedBidirectionalId(2)) != nullptr);
681   ASSERT_TRUE(session_.GetOrCreateStream(
682                   GetNthClientInitiatedBidirectionalId(1)) != nullptr);
683 }
684 
TEST_P(QuicSessionTestServer,AvailableUnidirectionalStreams)685 TEST_P(QuicSessionTestServer, AvailableUnidirectionalStreams) {
686   ASSERT_TRUE(session_.GetOrCreateStream(
687                   GetNthClientInitiatedUnidirectionalId(3)) != nullptr);
688   // Smaller unidirectional streams should be available.
689   EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
690       &session_, GetNthClientInitiatedUnidirectionalId(1)));
691   EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
692       &session_, GetNthClientInitiatedUnidirectionalId(2)));
693   ASSERT_TRUE(session_.GetOrCreateStream(
694                   GetNthClientInitiatedUnidirectionalId(2)) != nullptr);
695   ASSERT_TRUE(session_.GetOrCreateStream(
696                   GetNthClientInitiatedUnidirectionalId(1)) != nullptr);
697 }
698 
TEST_P(QuicSessionTestServer,MaxAvailableBidirectionalStreams)699 TEST_P(QuicSessionTestServer, MaxAvailableBidirectionalStreams) {
700   if (VersionHasIetfQuicFrames(transport_version())) {
701     EXPECT_EQ(session_.max_open_incoming_bidirectional_streams(),
702               session_.MaxAvailableBidirectionalStreams());
703   } else {
704     // The protocol specification requires that there can be at least 10 times
705     // as many available streams as the connection's maximum open streams.
706     EXPECT_EQ(session_.max_open_incoming_bidirectional_streams() *
707                   kMaxAvailableStreamsMultiplier,
708               session_.MaxAvailableBidirectionalStreams());
709   }
710 }
711 
TEST_P(QuicSessionTestServer,MaxAvailableUnidirectionalStreams)712 TEST_P(QuicSessionTestServer, MaxAvailableUnidirectionalStreams) {
713   if (VersionHasIetfQuicFrames(transport_version())) {
714     EXPECT_EQ(session_.max_open_incoming_unidirectional_streams(),
715               session_.MaxAvailableUnidirectionalStreams());
716   } else {
717     // The protocol specification requires that there can be at least 10 times
718     // as many available streams as the connection's maximum open streams.
719     EXPECT_EQ(session_.max_open_incoming_unidirectional_streams() *
720                   kMaxAvailableStreamsMultiplier,
721               session_.MaxAvailableUnidirectionalStreams());
722   }
723 }
724 
TEST_P(QuicSessionTestServer,IsClosedBidirectionalStreamLocallyCreated)725 TEST_P(QuicSessionTestServer, IsClosedBidirectionalStreamLocallyCreated) {
726   CompleteHandshake();
727   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
728   EXPECT_EQ(GetNthServerInitiatedBidirectionalId(0), stream2->id());
729   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
730   EXPECT_EQ(GetNthServerInitiatedBidirectionalId(1), stream4->id());
731 
732   CheckClosedStreams();
733   CloseStream(GetNthServerInitiatedBidirectionalId(0));
734   CheckClosedStreams();
735   CloseStream(GetNthServerInitiatedBidirectionalId(1));
736   CheckClosedStreams();
737 }
738 
TEST_P(QuicSessionTestServer,IsClosedUnidirectionalStreamLocallyCreated)739 TEST_P(QuicSessionTestServer, IsClosedUnidirectionalStreamLocallyCreated) {
740   CompleteHandshake();
741   TestStream* stream2 = session_.CreateOutgoingUnidirectionalStream();
742   EXPECT_EQ(GetNthServerInitiatedUnidirectionalId(0), stream2->id());
743   TestStream* stream4 = session_.CreateOutgoingUnidirectionalStream();
744   EXPECT_EQ(GetNthServerInitiatedUnidirectionalId(1), stream4->id());
745 
746   CheckClosedStreams();
747   CloseStream(GetNthServerInitiatedUnidirectionalId(0));
748   CheckClosedStreams();
749   CloseStream(GetNthServerInitiatedUnidirectionalId(1));
750   CheckClosedStreams();
751 }
752 
TEST_P(QuicSessionTestServer,IsClosedBidirectionalStreamPeerCreated)753 TEST_P(QuicSessionTestServer, IsClosedBidirectionalStreamPeerCreated) {
754   CompleteHandshake();
755   QuicStreamId stream_id1 = GetNthClientInitiatedBidirectionalId(0);
756   QuicStreamId stream_id2 = GetNthClientInitiatedBidirectionalId(1);
757   session_.GetOrCreateStream(stream_id1);
758   session_.GetOrCreateStream(stream_id2);
759 
760   CheckClosedStreams();
761   CloseStream(stream_id1);
762   CheckClosedStreams();
763   CloseStream(stream_id2);
764   // Create a stream, and make another available.
765   QuicStream* stream3 = session_.GetOrCreateStream(
766       stream_id2 +
767       2 * QuicUtils::StreamIdDelta(connection_->transport_version()));
768   CheckClosedStreams();
769   // Close one, but make sure the other is still not closed
770   CloseStream(stream3->id());
771   CheckClosedStreams();
772 }
773 
TEST_P(QuicSessionTestServer,IsClosedUnidirectionalStreamPeerCreated)774 TEST_P(QuicSessionTestServer, IsClosedUnidirectionalStreamPeerCreated) {
775   CompleteHandshake();
776   QuicStreamId stream_id1 = GetNthClientInitiatedUnidirectionalId(0);
777   QuicStreamId stream_id2 = GetNthClientInitiatedUnidirectionalId(1);
778   session_.GetOrCreateStream(stream_id1);
779   session_.GetOrCreateStream(stream_id2);
780 
781   CheckClosedStreams();
782   CloseStream(stream_id1);
783   CheckClosedStreams();
784   CloseStream(stream_id2);
785   // Create a stream, and make another available.
786   QuicStream* stream3 = session_.GetOrCreateStream(
787       stream_id2 +
788       2 * QuicUtils::StreamIdDelta(connection_->transport_version()));
789   CheckClosedStreams();
790   // Close one, but make sure the other is still not closed
791   CloseStream(stream3->id());
792   CheckClosedStreams();
793 }
794 
TEST_P(QuicSessionTestServer,MaximumAvailableOpenedBidirectionalStreams)795 TEST_P(QuicSessionTestServer, MaximumAvailableOpenedBidirectionalStreams) {
796   QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
797   session_.GetOrCreateStream(stream_id);
798   EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
799   EXPECT_NE(nullptr,
800             session_.GetOrCreateStream(GetNthClientInitiatedBidirectionalId(
801                 session_.max_open_incoming_bidirectional_streams() - 1)));
802 }
803 
TEST_P(QuicSessionTestServer,MaximumAvailableOpenedUnidirectionalStreams)804 TEST_P(QuicSessionTestServer, MaximumAvailableOpenedUnidirectionalStreams) {
805   QuicStreamId stream_id = GetNthClientInitiatedUnidirectionalId(0);
806   session_.GetOrCreateStream(stream_id);
807   EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
808   EXPECT_NE(nullptr,
809             session_.GetOrCreateStream(GetNthClientInitiatedUnidirectionalId(
810                 session_.max_open_incoming_unidirectional_streams() - 1)));
811 }
812 
TEST_P(QuicSessionTestServer,TooManyAvailableBidirectionalStreams)813 TEST_P(QuicSessionTestServer, TooManyAvailableBidirectionalStreams) {
814   QuicStreamId stream_id1 = GetNthClientInitiatedBidirectionalId(0);
815   QuicStreamId stream_id2;
816   EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id1));
817   // A stream ID which is too large to create.
818   stream_id2 = GetNthClientInitiatedBidirectionalId(
819       session_.MaxAvailableBidirectionalStreams() + 2);
820   if (VersionHasIetfQuicFrames(transport_version())) {
821     // IETF QUIC terminates the connection with invalid stream id
822     EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_STREAM_ID, _, _));
823   } else {
824     // other versions terminate the connection with
825     // QUIC_TOO_MANY_AVAILABLE_STREAMS.
826     EXPECT_CALL(*connection_,
827                 CloseConnection(QUIC_TOO_MANY_AVAILABLE_STREAMS, _, _));
828   }
829   EXPECT_EQ(nullptr, session_.GetOrCreateStream(stream_id2));
830 }
831 
TEST_P(QuicSessionTestServer,TooManyAvailableUnidirectionalStreams)832 TEST_P(QuicSessionTestServer, TooManyAvailableUnidirectionalStreams) {
833   QuicStreamId stream_id1 = GetNthClientInitiatedUnidirectionalId(0);
834   QuicStreamId stream_id2;
835   EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id1));
836   // A stream ID which is too large to create.
837   stream_id2 = GetNthClientInitiatedUnidirectionalId(
838       session_.MaxAvailableUnidirectionalStreams() + 2);
839   if (VersionHasIetfQuicFrames(transport_version())) {
840     // IETF QUIC terminates the connection with invalid stream id
841     EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_STREAM_ID, _, _));
842   } else {
843     // other versions terminate the connection with
844     // QUIC_TOO_MANY_AVAILABLE_STREAMS.
845     EXPECT_CALL(*connection_,
846                 CloseConnection(QUIC_TOO_MANY_AVAILABLE_STREAMS, _, _));
847   }
848   EXPECT_EQ(nullptr, session_.GetOrCreateStream(stream_id2));
849 }
850 
TEST_P(QuicSessionTestServer,ManyAvailableBidirectionalStreams)851 TEST_P(QuicSessionTestServer, ManyAvailableBidirectionalStreams) {
852   // When max_open_streams_ is 200, should be able to create 200 streams
853   // out-of-order, that is, creating the one with the largest stream ID first.
854   if (VersionHasIetfQuicFrames(transport_version())) {
855     QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_, 200);
856     // Smaller limit on unidirectional streams to help detect crossed wires.
857     QuicSessionPeer::SetMaxOpenIncomingUnidirectionalStreams(&session_, 50);
858   } else {
859     QuicSessionPeer::SetMaxOpenIncomingStreams(&session_, 200);
860   }
861   // Create a stream at the start of the range.
862   QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
863   EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id));
864 
865   // Create the largest stream ID of a threatened total of 200 streams.
866   // GetNth... starts at 0, so for 200 streams, get the 199th.
867   EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
868   EXPECT_NE(nullptr, session_.GetOrCreateStream(
869                          GetNthClientInitiatedBidirectionalId(199)));
870 
871   if (VersionHasIetfQuicFrames(transport_version())) {
872     // If IETF QUIC, check to make sure that creating bidirectional
873     // streams does not mess up the unidirectional streams.
874     stream_id = GetNthClientInitiatedUnidirectionalId(0);
875     EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id));
876     // Now try to get the last possible unidirectional stream.
877     EXPECT_NE(nullptr, session_.GetOrCreateStream(
878                            GetNthClientInitiatedUnidirectionalId(49)));
879     // and this should fail because it exceeds the unidirectional limit
880     // (but not the bi-)
881     EXPECT_CALL(
882         *connection_,
883         CloseConnection(QUIC_INVALID_STREAM_ID,
884                         "Stream id 798 would exceed stream count limit 50",
885                         ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET))
886         .Times(1);
887     EXPECT_EQ(nullptr, session_.GetOrCreateStream(
888                            GetNthClientInitiatedUnidirectionalId(199)));
889   }
890 }
891 
TEST_P(QuicSessionTestServer,ManyAvailableUnidirectionalStreams)892 TEST_P(QuicSessionTestServer, ManyAvailableUnidirectionalStreams) {
893   // When max_open_streams_ is 200, should be able to create 200 streams
894   // out-of-order, that is, creating the one with the largest stream ID first.
895   if (VersionHasIetfQuicFrames(transport_version())) {
896     QuicSessionPeer::SetMaxOpenIncomingUnidirectionalStreams(&session_, 200);
897     // Smaller limit on unidirectional streams to help detect crossed wires.
898     QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_, 50);
899   } else {
900     QuicSessionPeer::SetMaxOpenIncomingStreams(&session_, 200);
901   }
902   // Create one stream.
903   QuicStreamId stream_id = GetNthClientInitiatedUnidirectionalId(0);
904   EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id));
905 
906   // Create the largest stream ID of a threatened total of 200 streams.
907   // GetNth... starts at 0, so for 200 streams, get the 199th.
908   EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
909   EXPECT_NE(nullptr, session_.GetOrCreateStream(
910                          GetNthClientInitiatedUnidirectionalId(199)));
911   if (VersionHasIetfQuicFrames(transport_version())) {
912     // If IETF QUIC, check to make sure that creating unidirectional
913     // streams does not mess up the bidirectional streams.
914     stream_id = GetNthClientInitiatedBidirectionalId(0);
915     EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id));
916     // Now try to get the last possible bidirectional stream.
917     EXPECT_NE(nullptr, session_.GetOrCreateStream(
918                            GetNthClientInitiatedBidirectionalId(49)));
919     // and this should fail because it exceeds the bnidirectional limit
920     // (but not the uni-)
921     std::string error_detail;
922     if (QuicVersionUsesCryptoFrames(transport_version())) {
923       error_detail = "Stream id 796 would exceed stream count limit 50";
924     } else {
925       error_detail = "Stream id 800 would exceed stream count limit 50";
926     }
927     EXPECT_CALL(
928         *connection_,
929         CloseConnection(QUIC_INVALID_STREAM_ID, error_detail,
930                         ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET))
931         .Times(1);
932     EXPECT_EQ(nullptr, session_.GetOrCreateStream(
933                            GetNthClientInitiatedBidirectionalId(199)));
934   }
935 }
936 
TEST_P(QuicSessionTestServer,DebugDFatalIfMarkingClosedStreamWriteBlocked)937 TEST_P(QuicSessionTestServer, DebugDFatalIfMarkingClosedStreamWriteBlocked) {
938   CompleteHandshake();
939   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
940   QuicStreamId closed_stream_id = stream2->id();
941   // Close the stream.
942   EXPECT_CALL(*connection_, SendControlFrame(_));
943   EXPECT_CALL(*connection_, OnStreamReset(closed_stream_id, _));
944   stream2->Reset(QUIC_BAD_APPLICATION_PAYLOAD);
945   std::string msg = quiche::QuicheStrCat("Marking unknown stream ",
946                                          closed_stream_id, " blocked.");
947   EXPECT_QUIC_BUG(session_.MarkConnectionLevelWriteBlocked(closed_stream_id),
948                   msg);
949 }
950 
TEST_P(QuicSessionTestServer,OnCanWrite)951 TEST_P(QuicSessionTestServer, OnCanWrite) {
952   CompleteHandshake();
953   session_.set_writev_consumes_all_data(true);
954   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
955   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
956   TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
957 
958   session_.MarkConnectionLevelWriteBlocked(stream2->id());
959   session_.MarkConnectionLevelWriteBlocked(stream6->id());
960   session_.MarkConnectionLevelWriteBlocked(stream4->id());
961 
962   InSequence s;
963 
964   // Reregister, to test the loop limit.
965   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
966     session_.SendStreamData(stream2);
967     session_.MarkConnectionLevelWriteBlocked(stream2->id());
968   }));
969   // 2 will get called a second time as it didn't finish its block
970   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
971     session_.SendStreamData(stream2);
972   }));
973   EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() {
974     session_.SendStreamData(stream6);
975   }));
976   // 4 will not get called, as we exceeded the loop limit.
977   session_.OnCanWrite();
978   EXPECT_TRUE(session_.WillingAndAbleToWrite());
979 }
980 
TEST_P(QuicSessionTestServer,TestBatchedWrites)981 TEST_P(QuicSessionTestServer, TestBatchedWrites) {
982   session_.set_writev_consumes_all_data(true);
983   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
984   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
985   TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
986 
987   session_.set_writev_consumes_all_data(true);
988   session_.MarkConnectionLevelWriteBlocked(stream2->id());
989   session_.MarkConnectionLevelWriteBlocked(stream4->id());
990 
991   // With two sessions blocked, we should get two write calls.  They should both
992   // go to the first stream as it will only write 6k and mark itself blocked
993   // again.
994   InSequence s;
995   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
996     session_.SendLargeFakeData(stream2, 6000);
997     session_.MarkConnectionLevelWriteBlocked(stream2->id());
998   }));
999   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1000     session_.SendLargeFakeData(stream2, 6000);
1001     session_.MarkConnectionLevelWriteBlocked(stream2->id());
1002   }));
1003   session_.OnCanWrite();
1004 
1005   // We should get one more call for stream2, at which point it has used its
1006   // write quota and we move over to stream 4.
1007   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1008     session_.SendLargeFakeData(stream2, 6000);
1009     session_.MarkConnectionLevelWriteBlocked(stream2->id());
1010   }));
1011   EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1012     session_.SendLargeFakeData(stream4, 6000);
1013     session_.MarkConnectionLevelWriteBlocked(stream4->id());
1014   }));
1015   session_.OnCanWrite();
1016 
1017   // Now let stream 4 do the 2nd of its 3 writes, but add a block for a high
1018   // priority stream 6.  4 should be preempted.  6 will write but *not* block so
1019   // will cede back to 4.
1020   stream6->SetPriority(spdy::SpdyStreamPrecedence(kV3HighestPriority));
1021   EXPECT_CALL(*stream4, OnCanWrite())
1022       .WillOnce(Invoke([this, stream4, stream6]() {
1023         session_.SendLargeFakeData(stream4, 6000);
1024         session_.MarkConnectionLevelWriteBlocked(stream4->id());
1025         session_.MarkConnectionLevelWriteBlocked(stream6->id());
1026       }));
1027   EXPECT_CALL(*stream6, OnCanWrite())
1028       .WillOnce(Invoke([this, stream4, stream6]() {
1029         session_.SendStreamData(stream6);
1030         session_.SendLargeFakeData(stream4, 6000);
1031       }));
1032   session_.OnCanWrite();
1033 
1034   // Stream4 alread did 6k worth of writes, so after doing another 12k it should
1035   // cede and 2 should resume.
1036   EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1037     session_.SendLargeFakeData(stream4, 12000);
1038     session_.MarkConnectionLevelWriteBlocked(stream4->id());
1039   }));
1040   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1041     session_.SendLargeFakeData(stream2, 6000);
1042     session_.MarkConnectionLevelWriteBlocked(stream2->id());
1043   }));
1044   session_.OnCanWrite();
1045 }
1046 
TEST_P(QuicSessionTestServer,Http2Priority)1047 TEST_P(QuicSessionTestServer, Http2Priority) {
1048   if (VersionHasIetfQuicFrames(GetParam().transport_version)) {
1049     // The test is using HTTP/2 priority which is not supported in IETF QUIC.
1050     return;
1051   }
1052   QuicTagVector copt;
1053   copt.push_back(kH2PR);
1054   QuicConfigPeer::SetReceivedConnectionOptions(session_.config(), copt);
1055   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1056   session_.OnConfigNegotiated();
1057   ASSERT_TRUE(session_.use_http2_priority_write_scheduler());
1058 
1059   session_.set_writev_consumes_all_data(true);
1060   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1061   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1062   TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
1063 
1064   session_.set_writev_consumes_all_data(true);
1065   /*
1066            0
1067           /|\
1068          2 4 6
1069   */
1070   session_.MarkConnectionLevelWriteBlocked(stream2->id());
1071   session_.MarkConnectionLevelWriteBlocked(stream4->id());
1072   session_.MarkConnectionLevelWriteBlocked(stream6->id());
1073 
1074   // Verify streams are scheduled round robin.
1075   InSequence s;
1076   EXPECT_CALL(*stream2, OnCanWrite());
1077   EXPECT_CALL(*stream4, OnCanWrite());
1078   EXPECT_CALL(*stream6, OnCanWrite());
1079   session_.OnCanWrite();
1080 
1081   /*
1082            0
1083            |
1084            4
1085           / \
1086          2   6
1087   */
1088   // Update stream 4's priority.
1089   stream4->SetPriority(
1090       spdy::SpdyStreamPrecedence(0, spdy::kHttp2DefaultStreamWeight, true));
1091   session_.MarkConnectionLevelWriteBlocked(stream2->id());
1092   session_.MarkConnectionLevelWriteBlocked(stream4->id());
1093   session_.MarkConnectionLevelWriteBlocked(stream6->id());
1094 
1095   EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1096     session_.MarkConnectionLevelWriteBlocked(stream4->id());
1097   }));
1098   EXPECT_CALL(*stream4, OnCanWrite());
1099   EXPECT_CALL(*stream2, OnCanWrite());
1100   session_.OnCanWrite();
1101   EXPECT_CALL(*stream6, OnCanWrite());
1102   session_.OnCanWrite();
1103 
1104   /*
1105          0
1106          |
1107          6
1108          |
1109          4
1110          |
1111          2
1112   */
1113   // Update stream 6's priority.
1114   stream6->SetPriority(
1115       spdy::SpdyStreamPrecedence(0, spdy::kHttp2DefaultStreamWeight, true));
1116   session_.MarkConnectionLevelWriteBlocked(stream2->id());
1117   session_.MarkConnectionLevelWriteBlocked(stream4->id());
1118   session_.MarkConnectionLevelWriteBlocked(stream6->id());
1119 
1120   EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() {
1121     session_.MarkConnectionLevelWriteBlocked(stream6->id());
1122   }));
1123   EXPECT_CALL(*stream6, OnCanWrite());
1124   EXPECT_CALL(*stream4, OnCanWrite());
1125   session_.OnCanWrite();
1126   EXPECT_CALL(*stream2, OnCanWrite());
1127   session_.OnCanWrite();
1128 }
1129 
TEST_P(QuicSessionTestServer,RoundRobinScheduling)1130 TEST_P(QuicSessionTestServer, RoundRobinScheduling) {
1131   if (VersionHasIetfQuicFrames(GetParam().transport_version)) {
1132     // IETF QUIC currently doesn't support PRIORITY.
1133     return;
1134   }
1135   QuicTagVector copt;
1136   copt.push_back(kRRWS);
1137   QuicConfigPeer::SetReceivedConnectionOptions(session_.config(), copt);
1138   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1139   session_.OnConfigNegotiated();
1140 
1141   session_.set_writev_consumes_all_data(true);
1142   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1143   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1144   TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
1145 
1146   session_.set_writev_consumes_all_data(true);
1147   session_.MarkConnectionLevelWriteBlocked(stream2->id());
1148   session_.MarkConnectionLevelWriteBlocked(stream4->id());
1149   session_.MarkConnectionLevelWriteBlocked(stream6->id());
1150 
1151   // Verify streams are scheduled round robin.
1152   InSequence s;
1153   EXPECT_CALL(*stream2, OnCanWrite());
1154   EXPECT_CALL(*stream4, OnCanWrite());
1155   EXPECT_CALL(*stream6, OnCanWrite());
1156   session_.OnCanWrite();
1157 
1158   /* 2, 4, 6, 8 */
1159   TestStream* stream8 = session_.CreateOutgoingBidirectionalStream();
1160 
1161   // Verify updated priority is ignored.
1162   stream4->SetPriority(spdy::SpdyStreamPrecedence(spdy::kV3HighestPriority));
1163   session_.MarkConnectionLevelWriteBlocked(stream8->id());
1164   session_.MarkConnectionLevelWriteBlocked(stream4->id());
1165   session_.MarkConnectionLevelWriteBlocked(stream2->id());
1166   session_.MarkConnectionLevelWriteBlocked(stream6->id());
1167 
1168   EXPECT_CALL(*stream8, OnCanWrite());
1169   EXPECT_CALL(*stream4, OnCanWrite());
1170   EXPECT_CALL(*stream2, OnCanWrite());
1171   EXPECT_CALL(*stream6, OnCanWrite());
1172   session_.OnCanWrite();
1173 }
1174 
TEST_P(QuicSessionTestServer,OnCanWriteBundlesStreams)1175 TEST_P(QuicSessionTestServer, OnCanWriteBundlesStreams) {
1176   // Encryption needs to be established before data can be sent.
1177   CompleteHandshake();
1178   MockPacketWriter* writer = static_cast<MockPacketWriter*>(
1179       QuicConnectionPeer::GetWriter(session_.connection()));
1180 
1181   // Drive congestion control manually.
1182   MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
1183   QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
1184 
1185   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1186   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1187   TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
1188 
1189   session_.MarkConnectionLevelWriteBlocked(stream2->id());
1190   session_.MarkConnectionLevelWriteBlocked(stream6->id());
1191   session_.MarkConnectionLevelWriteBlocked(stream4->id());
1192 
1193   EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(true));
1194   EXPECT_CALL(*send_algorithm, GetCongestionWindow())
1195       .WillRepeatedly(Return(kMaxOutgoingPacketSize * 10));
1196   EXPECT_CALL(*send_algorithm, InRecovery()).WillRepeatedly(Return(false));
1197   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1198     session_.SendStreamData(stream2);
1199   }));
1200   EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1201     session_.SendStreamData(stream4);
1202   }));
1203   EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() {
1204     session_.SendStreamData(stream6);
1205   }));
1206 
1207   // Expect that we only send one packet, the writes from different streams
1208   // should be bundled together.
1209   EXPECT_CALL(*writer, WritePacket(_, _, _, _, _))
1210       .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
1211   EXPECT_CALL(*send_algorithm, OnPacketSent(_, _, _, _, _));
1212   EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
1213   session_.OnCanWrite();
1214   EXPECT_FALSE(session_.WillingAndAbleToWrite());
1215 }
1216 
TEST_P(QuicSessionTestServer,OnCanWriteCongestionControlBlocks)1217 TEST_P(QuicSessionTestServer, OnCanWriteCongestionControlBlocks) {
1218   CompleteHandshake();
1219   session_.set_writev_consumes_all_data(true);
1220   InSequence s;
1221 
1222   // Drive congestion control manually.
1223   MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
1224   QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
1225 
1226   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1227   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1228   TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
1229 
1230   session_.MarkConnectionLevelWriteBlocked(stream2->id());
1231   session_.MarkConnectionLevelWriteBlocked(stream6->id());
1232   session_.MarkConnectionLevelWriteBlocked(stream4->id());
1233 
1234   EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
1235   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1236     session_.SendStreamData(stream2);
1237   }));
1238   EXPECT_CALL(*send_algorithm, GetCongestionWindow()).Times(AnyNumber());
1239   EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
1240   EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() {
1241     session_.SendStreamData(stream6);
1242   }));
1243   EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(false));
1244   // stream4->OnCanWrite is not called.
1245 
1246   session_.OnCanWrite();
1247   EXPECT_TRUE(session_.WillingAndAbleToWrite());
1248 
1249   // Still congestion-control blocked.
1250   EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(false));
1251   session_.OnCanWrite();
1252   EXPECT_TRUE(session_.WillingAndAbleToWrite());
1253 
1254   // stream4->OnCanWrite is called once the connection stops being
1255   // congestion-control blocked.
1256   EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
1257   EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1258     session_.SendStreamData(stream4);
1259   }));
1260   EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
1261   session_.OnCanWrite();
1262   EXPECT_FALSE(session_.WillingAndAbleToWrite());
1263 }
1264 
TEST_P(QuicSessionTestServer,OnCanWriteWriterBlocks)1265 TEST_P(QuicSessionTestServer, OnCanWriteWriterBlocks) {
1266   CompleteHandshake();
1267   // Drive congestion control manually in order to ensure that
1268   // application-limited signaling is handled correctly.
1269   MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
1270   QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
1271   EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(true));
1272 
1273   // Drive packet writer manually.
1274   MockPacketWriter* writer = static_cast<MockPacketWriter*>(
1275       QuicConnectionPeer::GetWriter(session_.connection()));
1276   EXPECT_CALL(*writer, IsWriteBlocked()).WillRepeatedly(Return(true));
1277   EXPECT_CALL(*writer, WritePacket(_, _, _, _, _)).Times(0);
1278 
1279   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1280 
1281   session_.MarkConnectionLevelWriteBlocked(stream2->id());
1282 
1283   EXPECT_CALL(*stream2, OnCanWrite()).Times(0);
1284   EXPECT_CALL(*send_algorithm, OnApplicationLimited(_)).Times(0);
1285 
1286   session_.OnCanWrite();
1287   EXPECT_TRUE(session_.WillingAndAbleToWrite());
1288 }
1289 
TEST_P(QuicSessionTestServer,SendStreamsBlocked)1290 TEST_P(QuicSessionTestServer, SendStreamsBlocked) {
1291   if (!VersionHasIetfQuicFrames(transport_version())) {
1292     return;
1293   }
1294   CompleteHandshake();
1295   for (size_t i = 0; i < kDefaultMaxStreamsPerConnection; ++i) {
1296     ASSERT_TRUE(session_.CanOpenNextOutgoingBidirectionalStream());
1297     session_.GetNextOutgoingBidirectionalStreamId();
1298   }
1299   // Next checking causes STREAMS_BLOCKED to be sent.
1300   EXPECT_CALL(*connection_, SendControlFrame(_))
1301       .WillOnce(Invoke([](const QuicFrame& frame) {
1302         EXPECT_FALSE(frame.streams_blocked_frame.unidirectional);
1303         EXPECT_EQ(kDefaultMaxStreamsPerConnection,
1304                   frame.streams_blocked_frame.stream_count);
1305         ClearControlFrame(frame);
1306         return true;
1307       }));
1308   EXPECT_FALSE(session_.CanOpenNextOutgoingBidirectionalStream());
1309 
1310   for (size_t i = 0; i < kDefaultMaxStreamsPerConnection; ++i) {
1311     ASSERT_TRUE(session_.CanOpenNextOutgoingUnidirectionalStream());
1312     session_.GetNextOutgoingUnidirectionalStreamId();
1313   }
1314   // Next checking causes STREAM_BLOCKED to be sent.
1315   EXPECT_CALL(*connection_, SendControlFrame(_))
1316       .WillOnce(Invoke([](const QuicFrame& frame) {
1317         EXPECT_TRUE(frame.streams_blocked_frame.unidirectional);
1318         EXPECT_EQ(kDefaultMaxStreamsPerConnection,
1319                   frame.streams_blocked_frame.stream_count);
1320         ClearControlFrame(frame);
1321         return true;
1322       }));
1323   EXPECT_FALSE(session_.CanOpenNextOutgoingUnidirectionalStream());
1324 }
1325 
TEST_P(QuicSessionTestServer,BufferedHandshake)1326 TEST_P(QuicSessionTestServer, BufferedHandshake) {
1327   // This test is testing behavior of crypto stream flow control, but when
1328   // CRYPTO frames are used, there is no flow control for the crypto handshake.
1329   if (QuicVersionUsesCryptoFrames(connection_->transport_version())) {
1330     return;
1331   }
1332   session_.set_writev_consumes_all_data(true);
1333   EXPECT_FALSE(session_.HasPendingHandshake());  // Default value.
1334 
1335   // Test that blocking other streams does not change our status.
1336   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1337   session_.MarkConnectionLevelWriteBlocked(stream2->id());
1338   EXPECT_FALSE(session_.HasPendingHandshake());
1339 
1340   TestStream* stream3 = session_.CreateOutgoingBidirectionalStream();
1341   session_.MarkConnectionLevelWriteBlocked(stream3->id());
1342   EXPECT_FALSE(session_.HasPendingHandshake());
1343 
1344   // Blocking (due to buffering of) the Crypto stream is detected.
1345   session_.MarkConnectionLevelWriteBlocked(
1346       QuicUtils::GetCryptoStreamId(connection_->transport_version()));
1347   EXPECT_TRUE(session_.HasPendingHandshake());
1348 
1349   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1350   session_.MarkConnectionLevelWriteBlocked(stream4->id());
1351   EXPECT_TRUE(session_.HasPendingHandshake());
1352 
1353   InSequence s;
1354   // Force most streams to re-register, which is common scenario when we block
1355   // the Crypto stream, and only the crypto stream can "really" write.
1356 
1357   // Due to prioritization, we *should* be asked to write the crypto stream
1358   // first.
1359   // Don't re-register the crypto stream (which signals complete writing).
1360   TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
1361   EXPECT_CALL(*crypto_stream, OnCanWrite());
1362 
1363   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1364     session_.SendStreamData(stream2);
1365   }));
1366   EXPECT_CALL(*stream3, OnCanWrite()).WillOnce(Invoke([this, stream3]() {
1367     session_.SendStreamData(stream3);
1368   }));
1369   EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1370     session_.SendStreamData(stream4);
1371     session_.MarkConnectionLevelWriteBlocked(stream4->id());
1372   }));
1373 
1374   session_.OnCanWrite();
1375   EXPECT_TRUE(session_.WillingAndAbleToWrite());
1376   EXPECT_FALSE(session_.HasPendingHandshake());  // Crypto stream wrote.
1377 }
1378 
TEST_P(QuicSessionTestServer,OnCanWriteWithClosedStream)1379 TEST_P(QuicSessionTestServer, OnCanWriteWithClosedStream) {
1380   CompleteHandshake();
1381   session_.set_writev_consumes_all_data(true);
1382   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1383   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1384   TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
1385 
1386   session_.MarkConnectionLevelWriteBlocked(stream2->id());
1387   session_.MarkConnectionLevelWriteBlocked(stream6->id());
1388   session_.MarkConnectionLevelWriteBlocked(stream4->id());
1389   CloseStream(stream6->id());
1390 
1391   InSequence s;
1392   EXPECT_CALL(*connection_, SendControlFrame(_))
1393       .WillRepeatedly(Invoke(&ClearControlFrame));
1394   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1395     session_.SendStreamData(stream2);
1396   }));
1397   EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1398     session_.SendStreamData(stream4);
1399   }));
1400   session_.OnCanWrite();
1401   EXPECT_FALSE(session_.WillingAndAbleToWrite());
1402 }
1403 
TEST_P(QuicSessionTestServer,OnCanWriteLimitsNumWritesIfFlowControlBlocked)1404 TEST_P(QuicSessionTestServer, OnCanWriteLimitsNumWritesIfFlowControlBlocked) {
1405   // Drive congestion control manually in order to ensure that
1406   // application-limited signaling is handled correctly.
1407   MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
1408   QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
1409   EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(true));
1410 
1411   // Ensure connection level flow control blockage.
1412   QuicFlowControllerPeer::SetSendWindowOffset(session_.flow_controller(), 0);
1413   EXPECT_TRUE(session_.flow_controller()->IsBlocked());
1414   EXPECT_TRUE(session_.IsConnectionFlowControlBlocked());
1415   EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
1416 
1417   // Mark the crypto and headers streams as write blocked, we expect them to be
1418   // allowed to write later.
1419   if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
1420     session_.MarkConnectionLevelWriteBlocked(
1421         QuicUtils::GetCryptoStreamId(connection_->transport_version()));
1422   }
1423 
1424   // Create a data stream, and although it is write blocked we never expect it
1425   // to be allowed to write as we are connection level flow control blocked.
1426   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1427   session_.MarkConnectionLevelWriteBlocked(stream->id());
1428   EXPECT_CALL(*stream, OnCanWrite()).Times(0);
1429 
1430   // The crypto and headers streams should be called even though we are
1431   // connection flow control blocked.
1432   if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
1433     TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
1434     EXPECT_CALL(*crypto_stream, OnCanWrite());
1435   }
1436 
1437   // After the crypto and header streams perform a write, the connection will be
1438   // blocked by the flow control, hence it should become application-limited.
1439   EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
1440 
1441   session_.OnCanWrite();
1442   EXPECT_FALSE(session_.WillingAndAbleToWrite());
1443 }
1444 
TEST_P(QuicSessionTestServer,SendGoAway)1445 TEST_P(QuicSessionTestServer, SendGoAway) {
1446   if (VersionHasIetfQuicFrames(transport_version())) {
1447     // In IETF QUIC, GOAWAY lives up in the HTTP layer.
1448     return;
1449   }
1450   CompleteHandshake();
1451   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1452   MockPacketWriter* writer = static_cast<MockPacketWriter*>(
1453       QuicConnectionPeer::GetWriter(session_.connection()));
1454   EXPECT_CALL(*writer, WritePacket(_, _, _, _, _))
1455       .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
1456 
1457   EXPECT_CALL(*connection_, SendControlFrame(_))
1458       .WillOnce(
1459           Invoke(connection_, &MockQuicConnection::ReallySendControlFrame));
1460   session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
1461   EXPECT_TRUE(session_.transport_goaway_sent());
1462 
1463   const QuicStreamId kTestStreamId = 5u;
1464   EXPECT_CALL(*connection_, SendControlFrame(_)).Times(0);
1465   EXPECT_CALL(*connection_,
1466               OnStreamReset(kTestStreamId, QUIC_STREAM_PEER_GOING_AWAY))
1467       .Times(0);
1468   EXPECT_TRUE(session_.GetOrCreateStream(kTestStreamId));
1469 }
1470 
TEST_P(QuicSessionTestServer,DoNotSendGoAwayTwice)1471 TEST_P(QuicSessionTestServer, DoNotSendGoAwayTwice) {
1472   CompleteHandshake();
1473   if (VersionHasIetfQuicFrames(transport_version())) {
1474     // In IETF QUIC, GOAWAY lives up in the HTTP layer.
1475     return;
1476   }
1477   EXPECT_CALL(*connection_, SendControlFrame(_))
1478       .WillOnce(Invoke(&ClearControlFrame));
1479   session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
1480   EXPECT_TRUE(session_.transport_goaway_sent());
1481   session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
1482 }
1483 
TEST_P(QuicSessionTestServer,InvalidGoAway)1484 TEST_P(QuicSessionTestServer, InvalidGoAway) {
1485   if (VersionHasIetfQuicFrames(transport_version())) {
1486     // In IETF QUIC, GOAWAY lives up in the HTTP layer.
1487     return;
1488   }
1489   QuicGoAwayFrame go_away(kInvalidControlFrameId, QUIC_PEER_GOING_AWAY,
1490                           session_.next_outgoing_bidirectional_stream_id(), "");
1491   session_.OnGoAway(go_away);
1492 }
1493 
1494 // Test that server session will send a connectivity probe in response to a
1495 // connectivity probe on the same path.
TEST_P(QuicSessionTestServer,ServerReplyToConnectivityProbe)1496 TEST_P(QuicSessionTestServer, ServerReplyToConnectivityProbe) {
1497   if (connection_->send_path_response() &&
1498       VersionHasIetfQuicFrames(transport_version())) {
1499     return;
1500   }
1501   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1502   QuicSocketAddress old_peer_address =
1503       QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort);
1504   EXPECT_EQ(old_peer_address, session_.peer_address());
1505 
1506   QuicSocketAddress new_peer_address =
1507       QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort + 1);
1508 
1509   MockPacketWriter* writer = static_cast<MockPacketWriter*>(
1510       QuicConnectionPeer::GetWriter(session_.connection()));
1511   EXPECT_CALL(*writer, WritePacket(_, _, _, new_peer_address, _))
1512       .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
1513   if (connection_->send_path_response()) {
1514     EXPECT_CALL(*connection_, SendConnectivityProbingPacket(_, _))
1515         .WillOnce(
1516             Invoke(connection_,
1517                    &MockQuicConnection::ReallySendConnectivityProbingPacket));
1518   } else {
1519     EXPECT_CALL(*connection_, SendConnectivityProbingResponsePacket(_))
1520         .WillOnce(Invoke(
1521             connection_,
1522             &MockQuicConnection::ReallySendConnectivityProbingResponsePacket));
1523   }
1524   if (VersionHasIetfQuicFrames(transport_version())) {
1525     // Need to explicitly do this to emulate the reception of a PathChallenge,
1526     // which stores its payload for use in generating the response.
1527     connection_->OnPathChallengeFrame(
1528         QuicPathChallengeFrame(0, path_frame_buffer1_));
1529   }
1530   session_.OnPacketReceived(session_.self_address(), new_peer_address,
1531                             /*is_connectivity_probe=*/true);
1532   EXPECT_EQ(old_peer_address, session_.peer_address());
1533 }
1534 
1535 // Same as above, but check that if there are two PATH_CHALLENGE frames in the
1536 // packet, the response has both of them AND we do not do migration.  This for
1537 // IETF QUIC only.
TEST_P(QuicSessionTestServer,ServerReplyToConnectivityProbes)1538 TEST_P(QuicSessionTestServer, ServerReplyToConnectivityProbes) {
1539   if (connection_->send_path_response() ||
1540       !VersionHasIetfQuicFrames(transport_version())) {
1541     return;
1542   }
1543   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1544   QuicSocketAddress old_peer_address =
1545       QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort);
1546   EXPECT_EQ(old_peer_address, session_.peer_address());
1547 
1548   MockPacketWriter* writer = static_cast<MockPacketWriter*>(
1549       QuicConnectionPeer::GetWriter(session_.connection()));
1550   // CheckMultiPathResponse validates that the written packet
1551   // contains both path responses.
1552   EXPECT_CALL(*writer, WritePacket(_, _, _, old_peer_address, _))
1553       .WillOnce(Invoke(this, &QuicSessionTestServer::CheckMultiPathResponse));
1554 
1555   EXPECT_CALL(*connection_, SendConnectivityProbingResponsePacket(_))
1556       .WillOnce(Invoke(
1557           connection_,
1558           &MockQuicConnection::ReallySendConnectivityProbingResponsePacket));
1559   QuicConnectionPeer::SetLastHeaderFormat(connection_,
1560                                           IETF_QUIC_SHORT_HEADER_PACKET);
1561   // Need to explicitly do this to emulate the reception of a PathChallenge,
1562   // which stores its payload for use in generating the response.
1563   connection_->OnPathChallengeFrame(
1564       QuicPathChallengeFrame(0, path_frame_buffer1_));
1565   connection_->OnPathChallengeFrame(
1566       QuicPathChallengeFrame(0, path_frame_buffer2_));
1567   session_.OnPacketReceived(session_.self_address(), old_peer_address,
1568                             /*is_connectivity_probe=*/true);
1569 }
1570 
TEST_P(QuicSessionTestServer,IncreasedTimeoutAfterCryptoHandshake)1571 TEST_P(QuicSessionTestServer, IncreasedTimeoutAfterCryptoHandshake) {
1572   EXPECT_EQ(kInitialIdleTimeoutSecs + 3,
1573             QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
1574   CompleteHandshake();
1575   EXPECT_EQ(kMaximumIdleTimeoutSecs + 3,
1576             QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
1577 }
1578 
TEST_P(QuicSessionTestServer,OnStreamFrameFinStaticStreamId)1579 TEST_P(QuicSessionTestServer, OnStreamFrameFinStaticStreamId) {
1580   if (VersionUsesHttp3(connection_->transport_version())) {
1581     // The test relies on headers stream, which no longer exists in IETF QUIC.
1582     return;
1583   }
1584   QuicStreamId headers_stream_id =
1585       QuicUtils::GetHeadersStreamId(connection_->transport_version());
1586   std::unique_ptr<TestStream> fake_headers_stream =
1587       std::make_unique<TestStream>(headers_stream_id, &session_,
1588                                    /*is_static*/ true, BIDIRECTIONAL);
1589   QuicSessionPeer::ActivateStream(&session_, std::move(fake_headers_stream));
1590   // Send two bytes of payload.
1591   QuicStreamFrame data1(headers_stream_id, true, 0, absl::string_view("HT"));
1592   EXPECT_CALL(*connection_,
1593               CloseConnection(
1594                   QUIC_INVALID_STREAM_ID, "Attempt to close a static stream",
1595                   ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
1596   session_.OnStreamFrame(data1);
1597 }
1598 
TEST_P(QuicSessionTestServer,OnStreamFrameInvalidStreamId)1599 TEST_P(QuicSessionTestServer, OnStreamFrameInvalidStreamId) {
1600   // Send two bytes of payload.
1601   QuicStreamFrame data1(
1602       QuicUtils::GetInvalidStreamId(connection_->transport_version()), true, 0,
1603       absl::string_view("HT"));
1604   EXPECT_CALL(*connection_,
1605               CloseConnection(
1606                   QUIC_INVALID_STREAM_ID, "Received data for an invalid stream",
1607                   ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
1608   session_.OnStreamFrame(data1);
1609 }
1610 
TEST_P(QuicSessionTestServer,OnRstStreamInvalidStreamId)1611 TEST_P(QuicSessionTestServer, OnRstStreamInvalidStreamId) {
1612   // Send two bytes of payload.
1613   QuicRstStreamFrame rst1(
1614       kInvalidControlFrameId,
1615       QuicUtils::GetInvalidStreamId(connection_->transport_version()),
1616       QUIC_ERROR_PROCESSING_STREAM, 0);
1617   EXPECT_CALL(*connection_,
1618               CloseConnection(
1619                   QUIC_INVALID_STREAM_ID, "Received data for an invalid stream",
1620                   ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
1621   session_.OnRstStream(rst1);
1622 }
1623 
TEST_P(QuicSessionTestServer,HandshakeUnblocksFlowControlBlockedStream)1624 TEST_P(QuicSessionTestServer, HandshakeUnblocksFlowControlBlockedStream) {
1625   if (connection_->version().handshake_protocol == PROTOCOL_TLS1_3) {
1626     // This test requires Google QUIC crypto because it assumes streams start
1627     // off unblocked.
1628     return;
1629   }
1630   // Test that if a stream is flow control blocked, then on receipt of the SHLO
1631   // containing a suitable send window offset, the stream becomes unblocked.
1632 
1633   // Ensure that Writev consumes all the data it is given (simulate no socket
1634   // blocking).
1635   session_.set_writev_consumes_all_data(true);
1636   session_.GetMutableCryptoStream()->EstablishZeroRttEncryption();
1637 
1638   // Create a stream, and send enough data to make it flow control blocked.
1639   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1640   std::string body(kMinimumFlowControlSendWindow, '.');
1641   EXPECT_FALSE(stream2->IsFlowControlBlocked());
1642   EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
1643   EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
1644   EXPECT_CALL(*connection_, SendControlFrame(_)).Times(AtLeast(1));
1645   stream2->WriteOrBufferData(body, false, nullptr);
1646   EXPECT_TRUE(stream2->IsFlowControlBlocked());
1647   EXPECT_TRUE(session_.IsConnectionFlowControlBlocked());
1648   EXPECT_TRUE(session_.IsStreamFlowControlBlocked());
1649 
1650   // Now complete the crypto handshake, resulting in an increased flow control
1651   // send window.
1652   CompleteHandshake();
1653   EXPECT_TRUE(QuicSessionPeer::IsStreamWriteBlocked(&session_, stream2->id()));
1654   // Stream is now unblocked.
1655   EXPECT_FALSE(stream2->IsFlowControlBlocked());
1656   EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
1657   EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
1658 }
1659 
TEST_P(QuicSessionTestServer,HandshakeUnblocksFlowControlBlockedCryptoStream)1660 TEST_P(QuicSessionTestServer, HandshakeUnblocksFlowControlBlockedCryptoStream) {
1661   if (QuicVersionUsesCryptoFrames(GetParam().transport_version) ||
1662       connection_->encrypted_control_frames()) {
1663     // QUIC version 47 onwards uses CRYPTO frames for the handshake, so this
1664     // test doesn't make sense for those versions since CRYPTO frames aren't
1665     // flow controlled.
1666     return;
1667   }
1668   // Test that if the crypto stream is flow control blocked, then if the SHLO
1669   // contains a larger send window offset, the stream becomes unblocked.
1670   session_.set_writev_consumes_all_data(true);
1671   TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
1672   EXPECT_FALSE(crypto_stream->IsFlowControlBlocked());
1673   EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
1674   EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
1675   EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
1676   EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
1677   EXPECT_CALL(*connection_, SendControlFrame(_))
1678       .WillOnce(Invoke(&ClearControlFrame));
1679   for (QuicStreamId i = 0; !crypto_stream->IsFlowControlBlocked() && i < 1000u;
1680        i++) {
1681     EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
1682     EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
1683     QuicStreamOffset offset = crypto_stream->stream_bytes_written();
1684     QuicConfig config;
1685     CryptoHandshakeMessage crypto_message;
1686     config.ToHandshakeMessage(&crypto_message, transport_version());
1687     crypto_stream->SendHandshakeMessage(crypto_message, ENCRYPTION_INITIAL);
1688     char buf[1000];
1689     QuicDataWriter writer(1000, buf, quiche::NETWORK_BYTE_ORDER);
1690     crypto_stream->WriteStreamData(offset, crypto_message.size(), &writer);
1691   }
1692   EXPECT_TRUE(crypto_stream->IsFlowControlBlocked());
1693   EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
1694   EXPECT_TRUE(session_.IsStreamFlowControlBlocked());
1695   EXPECT_FALSE(session_.HasDataToWrite());
1696   EXPECT_TRUE(crypto_stream->HasBufferedData());
1697 
1698   // Now complete the crypto handshake, resulting in an increased flow control
1699   // send window.
1700   CompleteHandshake();
1701   EXPECT_TRUE(QuicSessionPeer::IsStreamWriteBlocked(
1702       &session_,
1703       QuicUtils::GetCryptoStreamId(connection_->transport_version())));
1704   // Stream is now unblocked and will no longer have buffered data.
1705   EXPECT_FALSE(crypto_stream->IsFlowControlBlocked());
1706   EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
1707   EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
1708 }
1709 
TEST_P(QuicSessionTestServer,ConnectionFlowControlAccountingRstOutOfOrder)1710 TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingRstOutOfOrder) {
1711   CompleteHandshake();
1712   // Test that when we receive an out of order stream RST we correctly adjust
1713   // our connection level flow control receive window.
1714   // On close, the stream should mark as consumed all bytes between the highest
1715   // byte consumed so far and the final byte offset from the RST frame.
1716   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1717 
1718   const QuicStreamOffset kByteOffset =
1719       1 + kInitialSessionFlowControlWindowForTest / 2;
1720 
1721   EXPECT_CALL(*connection_, SendControlFrame(_))
1722       .Times(2)
1723       .WillRepeatedly(Invoke(&ClearControlFrame));
1724   EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
1725 
1726   QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream->id(),
1727                                QUIC_STREAM_CANCELLED, kByteOffset);
1728   session_.OnRstStream(rst_frame);
1729   if (VersionHasIetfQuicFrames(transport_version())) {
1730     // The test requires the stream to be fully closed in both directions. For
1731     // IETF QUIC, the RST_STREAM only closes one side.
1732     QuicStopSendingFrame frame(kInvalidControlFrameId, stream->id(),
1733                                QUIC_STREAM_CANCELLED);
1734     EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
1735     session_.OnStopSendingFrame(frame);
1736   }
1737   EXPECT_EQ(kByteOffset, session_.flow_controller()->bytes_consumed());
1738 }
1739 
TEST_P(QuicSessionTestServer,ConnectionFlowControlAccountingFinAndLocalReset)1740 TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingFinAndLocalReset) {
1741   CompleteHandshake();
1742   // Test the situation where we receive a FIN on a stream, and before we fully
1743   // consume all the data from the sequencer buffer we locally RST the stream.
1744   // The bytes between highest consumed byte, and the final byte offset that we
1745   // determined when the FIN arrived, should be marked as consumed at the
1746   // connection level flow controller when the stream is reset.
1747   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1748 
1749   const QuicStreamOffset kByteOffset =
1750       kInitialSessionFlowControlWindowForTest / 2 - 1;
1751   QuicStreamFrame frame(stream->id(), true, kByteOffset, ".");
1752   session_.OnStreamFrame(frame);
1753   EXPECT_TRUE(connection_->connected());
1754 
1755   EXPECT_EQ(0u, session_.flow_controller()->bytes_consumed());
1756   EXPECT_EQ(kByteOffset + frame.data_length,
1757             stream->highest_received_byte_offset());
1758 
1759   // Reset stream locally.
1760   EXPECT_CALL(*connection_, SendControlFrame(_));
1761   EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
1762   stream->Reset(QUIC_STREAM_CANCELLED);
1763   EXPECT_EQ(kByteOffset + frame.data_length,
1764             session_.flow_controller()->bytes_consumed());
1765 }
1766 
TEST_P(QuicSessionTestServer,ConnectionFlowControlAccountingFinAfterRst)1767 TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingFinAfterRst) {
1768   CompleteHandshake();
1769   // Test that when we RST the stream (and tear down stream state), and then
1770   // receive a FIN from the peer, we correctly adjust our connection level flow
1771   // control receive window.
1772 
1773   // Connection starts with some non-zero highest received byte offset,
1774   // due to other active streams.
1775   const uint64_t kInitialConnectionBytesConsumed = 567;
1776   const uint64_t kInitialConnectionHighestReceivedOffset = 1234;
1777   EXPECT_LT(kInitialConnectionBytesConsumed,
1778             kInitialConnectionHighestReceivedOffset);
1779   session_.flow_controller()->UpdateHighestReceivedOffset(
1780       kInitialConnectionHighestReceivedOffset);
1781   session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed);
1782 
1783   // Reset our stream: this results in the stream being closed locally.
1784   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1785   EXPECT_CALL(*connection_, SendControlFrame(_));
1786   EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
1787   stream->Reset(QUIC_STREAM_CANCELLED);
1788 
1789   // Now receive a response from the peer with a FIN. We should handle this by
1790   // adjusting the connection level flow control receive window to take into
1791   // account the total number of bytes sent by the peer.
1792   const QuicStreamOffset kByteOffset = 5678;
1793   std::string body = "hello";
1794   QuicStreamFrame frame(stream->id(), true, kByteOffset,
1795                         absl::string_view(body));
1796   session_.OnStreamFrame(frame);
1797 
1798   QuicStreamOffset total_stream_bytes_sent_by_peer =
1799       kByteOffset + body.length();
1800   EXPECT_EQ(kInitialConnectionBytesConsumed + total_stream_bytes_sent_by_peer,
1801             session_.flow_controller()->bytes_consumed());
1802   EXPECT_EQ(
1803       kInitialConnectionHighestReceivedOffset + total_stream_bytes_sent_by_peer,
1804       session_.flow_controller()->highest_received_byte_offset());
1805 }
1806 
TEST_P(QuicSessionTestServer,ConnectionFlowControlAccountingRstAfterRst)1807 TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingRstAfterRst) {
1808   CompleteHandshake();
1809   // Test that when we RST the stream (and tear down stream state), and then
1810   // receive a RST from the peer, we correctly adjust our connection level flow
1811   // control receive window.
1812 
1813   // Connection starts with some non-zero highest received byte offset,
1814   // due to other active streams.
1815   const uint64_t kInitialConnectionBytesConsumed = 567;
1816   const uint64_t kInitialConnectionHighestReceivedOffset = 1234;
1817   EXPECT_LT(kInitialConnectionBytesConsumed,
1818             kInitialConnectionHighestReceivedOffset);
1819   session_.flow_controller()->UpdateHighestReceivedOffset(
1820       kInitialConnectionHighestReceivedOffset);
1821   session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed);
1822 
1823   // Reset our stream: this results in the stream being closed locally.
1824   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1825   EXPECT_CALL(*connection_, SendControlFrame(_));
1826   EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
1827   stream->Reset(QUIC_STREAM_CANCELLED);
1828   EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream));
1829 
1830   // Now receive a RST from the peer. We should handle this by adjusting the
1831   // connection level flow control receive window to take into account the total
1832   // number of bytes sent by the peer.
1833   const QuicStreamOffset kByteOffset = 5678;
1834   QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream->id(),
1835                                QUIC_STREAM_CANCELLED, kByteOffset);
1836   session_.OnRstStream(rst_frame);
1837 
1838   EXPECT_EQ(kInitialConnectionBytesConsumed + kByteOffset,
1839             session_.flow_controller()->bytes_consumed());
1840   EXPECT_EQ(kInitialConnectionHighestReceivedOffset + kByteOffset,
1841             session_.flow_controller()->highest_received_byte_offset());
1842 }
1843 
TEST_P(QuicSessionTestServer,InvalidStreamFlowControlWindowInHandshake)1844 TEST_P(QuicSessionTestServer, InvalidStreamFlowControlWindowInHandshake) {
1845   // Test that receipt of an invalid (< default) stream flow control window from
1846   // the peer results in the connection being torn down.
1847   const uint32_t kInvalidWindow = kMinimumFlowControlSendWindow - 1;
1848   QuicConfigPeer::SetReceivedInitialStreamFlowControlWindow(session_.config(),
1849                                                             kInvalidWindow);
1850 
1851   if (connection_->version().handshake_protocol != PROTOCOL_TLS1_3) {
1852     EXPECT_CALL(*connection_,
1853                 CloseConnection(QUIC_FLOW_CONTROL_INVALID_WINDOW, _, _));
1854   } else {
1855     EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
1856   }
1857   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1858   session_.OnConfigNegotiated();
1859 }
1860 
1861 // Test negotiation of custom server initial flow control window.
TEST_P(QuicSessionTestServer,CustomFlowControlWindow)1862 TEST_P(QuicSessionTestServer, CustomFlowControlWindow) {
1863   QuicTagVector copt;
1864   copt.push_back(kIFW7);
1865   QuicConfigPeer::SetReceivedConnectionOptions(session_.config(), copt);
1866 
1867   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1868   session_.OnConfigNegotiated();
1869   EXPECT_EQ(192 * 1024u, QuicFlowControllerPeer::ReceiveWindowSize(
1870                              session_.flow_controller()));
1871 }
1872 
TEST_P(QuicSessionTestServer,FlowControlWithInvalidFinalOffset)1873 TEST_P(QuicSessionTestServer, FlowControlWithInvalidFinalOffset) {
1874   CompleteHandshake();
1875   // Test that if we receive a stream RST with a highest byte offset that
1876   // violates flow control, that we close the connection.
1877   const uint64_t kLargeOffset = kInitialSessionFlowControlWindowForTest + 1;
1878   EXPECT_CALL(*connection_,
1879               CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _))
1880       .Times(2);
1881 
1882   // Check that stream frame + FIN results in connection close.
1883   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1884   EXPECT_CALL(*connection_, SendControlFrame(_));
1885   EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
1886   stream->Reset(QUIC_STREAM_CANCELLED);
1887   QuicStreamFrame frame(stream->id(), true, kLargeOffset, absl::string_view());
1888   session_.OnStreamFrame(frame);
1889 
1890   // Check that RST results in connection close.
1891   QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream->id(),
1892                                QUIC_STREAM_CANCELLED, kLargeOffset);
1893   session_.OnRstStream(rst_frame);
1894 }
1895 
TEST_P(QuicSessionTestServer,TooManyUnfinishedStreamsCauseServerRejectStream)1896 TEST_P(QuicSessionTestServer, TooManyUnfinishedStreamsCauseServerRejectStream) {
1897   CompleteHandshake();
1898   // If a buggy/malicious peer creates too many streams that are not ended
1899   // with a FIN or RST then we send an RST to refuse streams. For IETF QUIC the
1900   // connection is closed.
1901   const QuicStreamId kMaxStreams = 5;
1902   if (VersionHasIetfQuicFrames(transport_version())) {
1903     QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_,
1904                                                             kMaxStreams);
1905   } else {
1906     QuicSessionPeer::SetMaxOpenIncomingStreams(&session_, kMaxStreams);
1907   }
1908   const QuicStreamId kFirstStreamId = GetNthClientInitiatedBidirectionalId(0);
1909   const QuicStreamId kFinalStreamId =
1910       GetNthClientInitiatedBidirectionalId(kMaxStreams);
1911   // Create kMaxStreams data streams, and close them all without receiving a
1912   // FIN or a RST_STREAM from the client.
1913   for (QuicStreamId i = kFirstStreamId; i < kFinalStreamId;
1914        i += QuicUtils::StreamIdDelta(connection_->transport_version())) {
1915     QuicStreamFrame data1(i, false, 0, absl::string_view("HT"));
1916     session_.OnStreamFrame(data1);
1917     CloseStream(i);
1918   }
1919 
1920   if (VersionHasIetfQuicFrames(transport_version())) {
1921     EXPECT_CALL(
1922         *connection_,
1923         CloseConnection(QUIC_INVALID_STREAM_ID,
1924                         "Stream id 20 would exceed stream count limit 5", _));
1925   } else {
1926     EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1);
1927     EXPECT_CALL(*connection_,
1928                 OnStreamReset(kFinalStreamId, QUIC_REFUSED_STREAM))
1929         .Times(1);
1930   }
1931   // Create one more data streams to exceed limit of open stream.
1932   QuicStreamFrame data1(kFinalStreamId, false, 0, absl::string_view("HT"));
1933   session_.OnStreamFrame(data1);
1934 }
1935 
TEST_P(QuicSessionTestServer,DrainingStreamsDoNotCountAsOpenedOutgoing)1936 TEST_P(QuicSessionTestServer, DrainingStreamsDoNotCountAsOpenedOutgoing) {
1937   // Verify that a draining stream (which has received a FIN but not consumed
1938   // it) does not count against the open quota (because it is closed from the
1939   // protocol point of view).
1940   CompleteHandshake();
1941   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1942   QuicStreamId stream_id = stream->id();
1943   QuicStreamFrame data1(stream_id, true, 0, absl::string_view("HT"));
1944   session_.OnStreamFrame(data1);
1945   EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1);
1946   session_.StreamDraining(stream_id, /*unidirectional=*/false);
1947 }
1948 
TEST_P(QuicSessionTestServer,NoPendingStreams)1949 TEST_P(QuicSessionTestServer, NoPendingStreams) {
1950   session_.set_uses_pending_streams(false);
1951 
1952   QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
1953       transport_version(), Perspective::IS_CLIENT);
1954   QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT"));
1955   session_.OnStreamFrame(data1);
1956   EXPECT_EQ(1, session_.num_incoming_streams_created());
1957 
1958   QuicStreamFrame data2(stream_id, false, 0, absl::string_view("HT"));
1959   session_.OnStreamFrame(data2);
1960   EXPECT_EQ(1, session_.num_incoming_streams_created());
1961 }
1962 
TEST_P(QuicSessionTestServer,PendingStreams)1963 TEST_P(QuicSessionTestServer, PendingStreams) {
1964   if (!VersionUsesHttp3(transport_version())) {
1965     return;
1966   }
1967   session_.set_uses_pending_streams(true);
1968 
1969   QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
1970       transport_version(), Perspective::IS_CLIENT);
1971   QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT"));
1972   session_.OnStreamFrame(data1);
1973   EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
1974   EXPECT_EQ(0, session_.num_incoming_streams_created());
1975 
1976   QuicStreamFrame data2(stream_id, false, 0, absl::string_view("HT"));
1977   session_.OnStreamFrame(data2);
1978   EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
1979   EXPECT_EQ(1, session_.num_incoming_streams_created());
1980 }
1981 
TEST_P(QuicSessionTestServer,RstPendingStreams)1982 TEST_P(QuicSessionTestServer, RstPendingStreams) {
1983   if (!VersionUsesHttp3(transport_version())) {
1984     return;
1985   }
1986   session_.set_uses_pending_streams(true);
1987 
1988   QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
1989       transport_version(), Perspective::IS_CLIENT);
1990   QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT"));
1991   session_.OnStreamFrame(data1);
1992   EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
1993   EXPECT_EQ(0, session_.num_incoming_streams_created());
1994   EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
1995 
1996   QuicRstStreamFrame rst1(kInvalidControlFrameId, stream_id,
1997                           QUIC_ERROR_PROCESSING_STREAM, 12);
1998   session_.OnRstStream(rst1);
1999   EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
2000   EXPECT_EQ(0, session_.num_incoming_streams_created());
2001   EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
2002 
2003   QuicStreamFrame data2(stream_id, false, 0, absl::string_view("HT"));
2004   session_.OnStreamFrame(data2);
2005   EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
2006   EXPECT_EQ(0, session_.num_incoming_streams_created());
2007   EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
2008 }
2009 
TEST_P(QuicSessionTestServer,OnFinPendingStreams)2010 TEST_P(QuicSessionTestServer, OnFinPendingStreams) {
2011   if (!VersionUsesHttp3(transport_version())) {
2012     return;
2013   }
2014   session_.set_uses_pending_streams(true);
2015 
2016   QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
2017       transport_version(), Perspective::IS_CLIENT);
2018   QuicStreamFrame data(stream_id, true, 0, "");
2019   session_.OnStreamFrame(data);
2020 
2021   EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
2022   EXPECT_EQ(0, session_.num_incoming_streams_created());
2023   EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
2024 }
2025 
TEST_P(QuicSessionTestServer,PendingStreamOnWindowUpdate)2026 TEST_P(QuicSessionTestServer, PendingStreamOnWindowUpdate) {
2027   if (!VersionUsesHttp3(transport_version())) {
2028     return;
2029   }
2030 
2031   session_.set_uses_pending_streams(true);
2032   QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
2033       transport_version(), Perspective::IS_CLIENT);
2034   QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT"));
2035   session_.OnStreamFrame(data1);
2036   EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
2037   EXPECT_EQ(0, session_.num_incoming_streams_created());
2038   QuicWindowUpdateFrame window_update_frame(kInvalidControlFrameId, stream_id,
2039                                             0);
2040   EXPECT_CALL(
2041       *connection_,
2042       CloseConnection(
2043           QUIC_WINDOW_UPDATE_RECEIVED_ON_READ_UNIDIRECTIONAL_STREAM,
2044           "WindowUpdateFrame received on READ_UNIDIRECTIONAL stream.", _));
2045   session_.OnWindowUpdateFrame(window_update_frame);
2046 }
2047 
TEST_P(QuicSessionTestServer,DrainingStreamsDoNotCountAsOpened)2048 TEST_P(QuicSessionTestServer, DrainingStreamsDoNotCountAsOpened) {
2049   // Verify that a draining stream (which has received a FIN but not consumed
2050   // it) does not count against the open quota (because it is closed from the
2051   // protocol point of view).
2052   CompleteHandshake();
2053   if (VersionHasIetfQuicFrames(transport_version())) {
2054     // On IETF QUIC, we will expect to see a MAX_STREAMS go out when there are
2055     // not enough streams to create the next one.
2056     EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1);
2057   } else {
2058     EXPECT_CALL(*connection_, SendControlFrame(_)).Times(0);
2059   }
2060   EXPECT_CALL(*connection_, OnStreamReset(_, QUIC_REFUSED_STREAM)).Times(0);
2061   const QuicStreamId kMaxStreams = 5;
2062   if (VersionHasIetfQuicFrames(transport_version())) {
2063     QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_,
2064                                                             kMaxStreams);
2065   } else {
2066     QuicSessionPeer::SetMaxOpenIncomingStreams(&session_, kMaxStreams);
2067   }
2068 
2069   // Create kMaxStreams + 1 data streams, and mark them draining.
2070   const QuicStreamId kFirstStreamId = GetNthClientInitiatedBidirectionalId(0);
2071   const QuicStreamId kFinalStreamId =
2072       GetNthClientInitiatedBidirectionalId(2 * kMaxStreams + 1);
2073   for (QuicStreamId i = kFirstStreamId; i < kFinalStreamId;
2074        i += QuicUtils::StreamIdDelta(connection_->transport_version())) {
2075     QuicStreamFrame data1(i, true, 0, absl::string_view("HT"));
2076     session_.OnStreamFrame(data1);
2077     EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
2078     session_.StreamDraining(i, /*unidirectional=*/false);
2079     EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
2080   }
2081 }
2082 
2083 class QuicSessionTestClient : public QuicSessionTestBase {
2084  protected:
QuicSessionTestClient()2085   QuicSessionTestClient()
2086       : QuicSessionTestBase(Perspective::IS_CLIENT,
2087                             /*configure_session=*/true) {}
2088 };
2089 
2090 INSTANTIATE_TEST_SUITE_P(Tests,
2091                          QuicSessionTestClient,
2092                          ::testing::ValuesIn(AllSupportedVersions()),
2093                          ::testing::PrintToStringParamName());
2094 
TEST_P(QuicSessionTestClient,AvailableBidirectionalStreamsClient)2095 TEST_P(QuicSessionTestClient, AvailableBidirectionalStreamsClient) {
2096   ASSERT_TRUE(session_.GetOrCreateStream(
2097                   GetNthServerInitiatedBidirectionalId(2)) != nullptr);
2098   // Smaller bidirectional streams should be available.
2099   EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
2100       &session_, GetNthServerInitiatedBidirectionalId(0)));
2101   EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
2102       &session_, GetNthServerInitiatedBidirectionalId(1)));
2103   ASSERT_TRUE(session_.GetOrCreateStream(
2104                   GetNthServerInitiatedBidirectionalId(0)) != nullptr);
2105   ASSERT_TRUE(session_.GetOrCreateStream(
2106                   GetNthServerInitiatedBidirectionalId(1)) != nullptr);
2107   // And 5 should be not available.
2108   EXPECT_FALSE(QuicSessionPeer::IsStreamAvailable(
2109       &session_, GetNthClientInitiatedBidirectionalId(1)));
2110 }
2111 
TEST_P(QuicSessionTestClient,InvalidSessionFlowControlWindowInHandshake)2112 TEST_P(QuicSessionTestClient, InvalidSessionFlowControlWindowInHandshake) {
2113   // Test that receipt of an invalid (< default for gQUIC, < current for TLS)
2114   // session flow control window from the peer results in the connection being
2115   // torn down.
2116   const uint32_t kInvalidWindow = kMinimumFlowControlSendWindow - 1;
2117   QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(session_.config(),
2118                                                              kInvalidWindow);
2119   EXPECT_CALL(
2120       *connection_,
2121       CloseConnection(connection_->version().AllowsLowFlowControlLimits()
2122                           ? QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED
2123                           : QUIC_FLOW_CONTROL_INVALID_WINDOW,
2124                       _, _));
2125   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2126   session_.OnConfigNegotiated();
2127 }
2128 
TEST_P(QuicSessionTestClient,InvalidBidiStreamLimitInHandshake)2129 TEST_P(QuicSessionTestClient, InvalidBidiStreamLimitInHandshake) {
2130   // IETF QUIC only feature.
2131   if (!VersionHasIetfQuicFrames(transport_version())) {
2132     return;
2133   }
2134   QuicConfigPeer::SetReceivedMaxBidirectionalStreams(
2135       session_.config(), kDefaultMaxStreamsPerConnection - 1);
2136   EXPECT_CALL(*connection_,
2137               CloseConnection(QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, _, _));
2138   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2139   session_.OnConfigNegotiated();
2140 }
2141 
TEST_P(QuicSessionTestClient,InvalidUniStreamLimitInHandshake)2142 TEST_P(QuicSessionTestClient, InvalidUniStreamLimitInHandshake) {
2143   // IETF QUIC only feature.
2144   if (!VersionHasIetfQuicFrames(transport_version())) {
2145     return;
2146   }
2147   QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(
2148       session_.config(), kDefaultMaxStreamsPerConnection - 1);
2149   EXPECT_CALL(*connection_,
2150               CloseConnection(QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, _, _));
2151   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2152   session_.OnConfigNegotiated();
2153 }
2154 
TEST_P(QuicSessionTestClient,InvalidStreamFlowControlWindowInHandshake)2155 TEST_P(QuicSessionTestClient, InvalidStreamFlowControlWindowInHandshake) {
2156   // IETF QUIC only feature.
2157   if (!VersionHasIetfQuicFrames(transport_version())) {
2158     return;
2159   }
2160   session_.CreateOutgoingBidirectionalStream();
2161   session_.CreateOutgoingBidirectionalStream();
2162   QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional(
2163       session_.config(), kMinimumFlowControlSendWindow - 1);
2164 
2165   EXPECT_CALL(*connection_, CloseConnection(_, _, _))
2166       .WillOnce(
2167           Invoke(connection_, &MockQuicConnection::ReallyCloseConnection));
2168   EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _));
2169 
2170   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2171   session_.OnConfigNegotiated();
2172 }
2173 
TEST_P(QuicSessionTestClient,OnMaxStreamFrame)2174 TEST_P(QuicSessionTestClient, OnMaxStreamFrame) {
2175   if (!VersionUsesHttp3(transport_version())) {
2176     return;
2177   }
2178   QuicMaxStreamsFrame frame;
2179   frame.unidirectional = false;
2180   frame.stream_count = 120;
2181   EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1);
2182   session_.OnMaxStreamsFrame(frame);
2183 
2184   QuicMaxStreamsFrame frame2;
2185   frame2.unidirectional = false;
2186   frame2.stream_count = 110;
2187   EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(0);
2188   session_.OnMaxStreamsFrame(frame2);
2189 }
2190 
TEST_P(QuicSessionTestClient,AvailableUnidirectionalStreamsClient)2191 TEST_P(QuicSessionTestClient, AvailableUnidirectionalStreamsClient) {
2192   ASSERT_TRUE(session_.GetOrCreateStream(
2193                   GetNthServerInitiatedUnidirectionalId(2)) != nullptr);
2194   // Smaller unidirectional streams should be available.
2195   EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
2196       &session_, GetNthServerInitiatedUnidirectionalId(0)));
2197   EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
2198       &session_, GetNthServerInitiatedUnidirectionalId(1)));
2199   ASSERT_TRUE(session_.GetOrCreateStream(
2200                   GetNthServerInitiatedUnidirectionalId(0)) != nullptr);
2201   ASSERT_TRUE(session_.GetOrCreateStream(
2202                   GetNthServerInitiatedUnidirectionalId(1)) != nullptr);
2203   // And 5 should be not available.
2204   EXPECT_FALSE(QuicSessionPeer::IsStreamAvailable(
2205       &session_, GetNthClientInitiatedUnidirectionalId(1)));
2206 }
2207 
TEST_P(QuicSessionTestClient,RecordFinAfterReadSideClosed)2208 TEST_P(QuicSessionTestClient, RecordFinAfterReadSideClosed) {
2209   CompleteHandshake();
2210   // Verify that an incoming FIN is recorded in a stream object even if the read
2211   // side has been closed.  This prevents an entry from being made in
2212   // locally_closed_streams_highest_offset_ (which will never be deleted).
2213   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
2214   QuicStreamId stream_id = stream->id();
2215 
2216   // Close the read side manually.
2217   QuicStreamPeer::CloseReadSide(stream);
2218 
2219   // Receive a stream data frame with FIN.
2220   QuicStreamFrame frame(stream_id, true, 0, absl::string_view());
2221   session_.OnStreamFrame(frame);
2222   EXPECT_TRUE(stream->fin_received());
2223 
2224   // Reset stream locally.
2225   EXPECT_CALL(*connection_, SendControlFrame(_));
2226   EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
2227   stream->Reset(QUIC_STREAM_CANCELLED);
2228   EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream));
2229 
2230   EXPECT_TRUE(connection_->connected());
2231   EXPECT_TRUE(QuicSessionPeer::IsStreamClosed(&session_, stream_id));
2232   EXPECT_FALSE(QuicSessionPeer::IsStreamCreated(&session_, stream_id));
2233 
2234   // The stream is not waiting for the arrival of the peer's final offset as it
2235   // was received with the FIN earlier.
2236   EXPECT_EQ(
2237       0u,
2238       QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(&session_).size());
2239 }
2240 
TEST_P(QuicSessionTestClient,IncomingStreamWithClientInitiatedStreamId)2241 TEST_P(QuicSessionTestClient, IncomingStreamWithClientInitiatedStreamId) {
2242   const QuicErrorCode expected_error =
2243       VersionHasIetfQuicFrames(transport_version())
2244           ? QUIC_HTTP_STREAM_WRONG_DIRECTION
2245           : QUIC_INVALID_STREAM_ID;
2246   EXPECT_CALL(
2247       *connection_,
2248       CloseConnection(expected_error, "Data for nonexistent stream",
2249                       ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
2250 
2251   QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(1),
2252                         /* fin = */ false, /* offset = */ 0,
2253                         absl::string_view("foo"));
2254   session_.OnStreamFrame(frame);
2255 }
2256 
TEST_P(QuicSessionTestClient,MinAckDelaySetOnTheClientQuicConfig)2257 TEST_P(QuicSessionTestClient, MinAckDelaySetOnTheClientQuicConfig) {
2258   if (!session_.version().HasIetfQuicFrames()) {
2259     return;
2260   }
2261   session_.config()->SetClientConnectionOptions({kAFFE});
2262   session_.Initialize();
2263   ASSERT_EQ(session_.config()->GetMinAckDelayToSendMs(),
2264             kDefaultMinAckDelayTimeMs);
2265   ASSERT_TRUE(session_.connection()->can_receive_ack_frequency_frame());
2266 }
2267 
TEST_P(QuicSessionTestClient,KeyUpdateFlagNotSet)2268 TEST_P(QuicSessionTestClient, KeyUpdateFlagNotSet) {
2269   SetQuicReloadableFlag(quic_key_update_supported, false);
2270   EXPECT_CALL(*session_.GetMutableCryptoStream(), KeyUpdateSupportedLocally())
2271       .Times(0);
2272   session_.Initialize();
2273   EXPECT_FALSE(session_.config()->KeyUpdateSupportedLocally());
2274 }
2275 
TEST_P(QuicSessionTestClient,KeyUpdateNotSupportedLocallyAndFlagSet)2276 TEST_P(QuicSessionTestClient, KeyUpdateNotSupportedLocallyAndFlagSet) {
2277   SetQuicReloadableFlag(quic_key_update_supported, true);
2278   EXPECT_CALL(*session_.GetMutableCryptoStream(), KeyUpdateSupportedLocally())
2279       .WillOnce(Return(false));
2280   session_.Initialize();
2281   EXPECT_FALSE(session_.config()->KeyUpdateSupportedLocally());
2282 }
2283 
TEST_P(QuicSessionTestClient,KeyUpdateSupportedLocallyAndFlagSet)2284 TEST_P(QuicSessionTestClient, KeyUpdateSupportedLocallyAndFlagSet) {
2285   SetQuicReloadableFlag(quic_key_update_supported, true);
2286   EXPECT_CALL(*session_.GetMutableCryptoStream(), KeyUpdateSupportedLocally())
2287       .WillOnce(Return(true));
2288   session_.Initialize();
2289   EXPECT_TRUE(session_.config()->KeyUpdateSupportedLocally());
2290 }
2291 
TEST_P(QuicSessionTestClient,FailedToCreateStreamIfTooCloseToIdleTimeout)2292 TEST_P(QuicSessionTestClient, FailedToCreateStreamIfTooCloseToIdleTimeout) {
2293   connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2294   EXPECT_TRUE(session_.CanOpenNextOutgoingBidirectionalStream());
2295   QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(connection_);
2296   ASSERT_TRUE(deadline.IsInitialized());
2297   QuicTime::Delta timeout = deadline - helper_.GetClock()->ApproximateNow();
2298   // Advance time to very close idle timeout.
2299   connection_->AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
2300   // Verify creation of new stream gets pushed back and connectivity probing
2301   // packet gets sent.
2302   EXPECT_CALL(*connection_, SendConnectivityProbingPacket(_, _)).Times(1);
2303   EXPECT_FALSE(session_.CanOpenNextOutgoingBidirectionalStream());
2304 
2305   // New packet gets received, idle deadline gets extended.
2306   EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false));
2307   QuicConnectionPeer::GetIdleNetworkDetector(connection_)
2308       .OnPacketReceived(helper_.GetClock()->ApproximateNow());
2309   session_.OnPacketDecrypted(ENCRYPTION_FORWARD_SECURE);
2310 
2311   EXPECT_TRUE(session_.CanOpenNextOutgoingBidirectionalStream());
2312 }
2313 
TEST_P(QuicSessionTestServer,ZombieStreams)2314 TEST_P(QuicSessionTestServer, ZombieStreams) {
2315   CompleteHandshake();
2316   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2317   QuicStreamPeer::SetStreamBytesWritten(3, stream2);
2318   EXPECT_TRUE(stream2->IsWaitingForAcks());
2319 
2320   CloseStream(stream2->id());
2321   ASSERT_EQ(1u, session_.closed_streams()->size());
2322   EXPECT_EQ(stream2->id(), session_.closed_streams()->front()->id());
2323   session_.MaybeCloseZombieStream(stream2->id());
2324   EXPECT_EQ(1u, session_.closed_streams()->size());
2325   EXPECT_EQ(stream2->id(), session_.closed_streams()->front()->id());
2326 }
2327 
TEST_P(QuicSessionTestServer,RstStreamReceivedAfterRstStreamSent)2328 TEST_P(QuicSessionTestServer, RstStreamReceivedAfterRstStreamSent) {
2329   CompleteHandshake();
2330   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2331   QuicStreamPeer::SetStreamBytesWritten(3, stream2);
2332   EXPECT_TRUE(stream2->IsWaitingForAcks());
2333 
2334   EXPECT_CALL(*connection_, SendControlFrame(_));
2335   EXPECT_CALL(*connection_, OnStreamReset(stream2->id(), _));
2336   EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(0);
2337   stream2->Reset(quic::QUIC_STREAM_CANCELLED);
2338 
2339   QuicRstStreamFrame rst1(kInvalidControlFrameId, stream2->id(),
2340                           QUIC_ERROR_PROCESSING_STREAM, 0);
2341   if (!VersionHasIetfQuicFrames(transport_version())) {
2342     EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1);
2343   }
2344   session_.OnRstStream(rst1);
2345 }
2346 
2347 // Regression test of b/71548958.
TEST_P(QuicSessionTestServer,TestZombieStreams)2348 TEST_P(QuicSessionTestServer, TestZombieStreams) {
2349   CompleteHandshake();
2350   session_.set_writev_consumes_all_data(true);
2351 
2352   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2353   std::string body(100, '.');
2354   stream2->WriteOrBufferData(body, false, nullptr);
2355   EXPECT_TRUE(stream2->IsWaitingForAcks());
2356   EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream2).size());
2357 
2358   QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream2->id(),
2359                                QUIC_STREAM_CANCELLED, 1234);
2360   // Just for the RST_STREAM
2361   EXPECT_CALL(*connection_, SendControlFrame(_))
2362       .WillOnce(Invoke(&ClearControlFrame));
2363   if (VersionHasIetfQuicFrames(transport_version())) {
2364     EXPECT_CALL(*connection_,
2365                 OnStreamReset(stream2->id(), QUIC_STREAM_CANCELLED));
2366   } else {
2367     EXPECT_CALL(*connection_,
2368                 OnStreamReset(stream2->id(), QUIC_RST_ACKNOWLEDGEMENT));
2369   }
2370   stream2->OnStreamReset(rst_frame);
2371 
2372   if (VersionHasIetfQuicFrames(transport_version())) {
2373     // The test requires the stream to be fully closed in both directions. For
2374     // IETF QUIC, the RST_STREAM only closes one side.
2375     QuicStopSendingFrame frame(kInvalidControlFrameId, stream2->id(),
2376                                QUIC_STREAM_CANCELLED);
2377     EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2378     session_.OnStopSendingFrame(frame);
2379   }
2380   ASSERT_EQ(1u, session_.closed_streams()->size());
2381   EXPECT_EQ(stream2->id(), session_.closed_streams()->front()->id());
2382 
2383   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
2384   if (VersionHasIetfQuicFrames(transport_version())) {
2385     // Once for the RST_STREAM, once for the STOP_SENDING
2386     EXPECT_CALL(*connection_, SendControlFrame(_))
2387         .Times(2)
2388         .WillRepeatedly(Invoke(&ClearControlFrame));
2389   } else {
2390     // Just for the RST_STREAM
2391     EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1);
2392   }
2393   EXPECT_CALL(*connection_,
2394               OnStreamReset(stream4->id(), QUIC_STREAM_CANCELLED));
2395   stream4->WriteOrBufferData(body, false, nullptr);
2396   // Note well: Reset() actually closes the stream in both directions. For
2397   // GOOGLE QUIC it sends a RST_STREAM (which does a 2-way close), for IETF
2398   // QUIC it sends both a RST_STREAM and a STOP_SENDING (each of which
2399   // closes in only one direction).
2400   stream4->Reset(QUIC_STREAM_CANCELLED);
2401   EXPECT_EQ(2u, session_.closed_streams()->size());
2402 }
2403 
TEST_P(QuicSessionTestServer,OnStreamFrameLost)2404 TEST_P(QuicSessionTestServer, OnStreamFrameLost) {
2405   CompleteHandshake();
2406   InSequence s;
2407 
2408   // Drive congestion control manually.
2409   MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
2410   QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
2411 
2412   TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
2413   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2414   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
2415 
2416   QuicStreamFrame frame1;
2417   if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
2418     frame1 = QuicStreamFrame(
2419         QuicUtils::GetCryptoStreamId(connection_->transport_version()), false,
2420         0, 1300);
2421   }
2422   QuicStreamFrame frame2(stream2->id(), false, 0, 9);
2423   QuicStreamFrame frame3(stream4->id(), false, 0, 9);
2424 
2425   // Lost data on cryption stream, streams 2 and 4.
2426   EXPECT_CALL(*stream4, HasPendingRetransmission()).WillOnce(Return(true));
2427   if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
2428     EXPECT_CALL(*crypto_stream, HasPendingRetransmission())
2429         .WillOnce(Return(true));
2430   }
2431   EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(true));
2432   session_.OnFrameLost(QuicFrame(frame3));
2433   if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
2434     session_.OnFrameLost(QuicFrame(frame1));
2435   } else {
2436     QuicCryptoFrame crypto_frame(ENCRYPTION_INITIAL, 0, 1300);
2437     session_.OnFrameLost(QuicFrame(&crypto_frame));
2438   }
2439   session_.OnFrameLost(QuicFrame(frame2));
2440   EXPECT_TRUE(session_.WillingAndAbleToWrite());
2441 
2442   // Mark streams 2 and 4 write blocked.
2443   session_.MarkConnectionLevelWriteBlocked(stream2->id());
2444   session_.MarkConnectionLevelWriteBlocked(stream4->id());
2445 
2446   // Lost data is retransmitted before new data, and retransmissions for crypto
2447   // stream go first.
2448   // Do not check congestion window when crypto stream has lost data.
2449   EXPECT_CALL(*send_algorithm, CanSend(_)).Times(0);
2450   if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
2451     EXPECT_CALL(*crypto_stream, OnCanWrite());
2452     EXPECT_CALL(*crypto_stream, HasPendingRetransmission())
2453         .WillOnce(Return(false));
2454   }
2455   // Check congestion window for non crypto streams.
2456   EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
2457   EXPECT_CALL(*stream4, OnCanWrite());
2458   EXPECT_CALL(*stream4, HasPendingRetransmission()).WillOnce(Return(false));
2459   // Connection is blocked.
2460   EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(false));
2461 
2462   session_.OnCanWrite();
2463   EXPECT_TRUE(session_.WillingAndAbleToWrite());
2464 
2465   // Unblock connection.
2466   // Stream 2 retransmits lost data.
2467   EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
2468   EXPECT_CALL(*stream2, OnCanWrite());
2469   EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(false));
2470   EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
2471   // Stream 2 sends new data.
2472   EXPECT_CALL(*stream2, OnCanWrite());
2473   EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
2474   EXPECT_CALL(*stream4, OnCanWrite());
2475   EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
2476 
2477   session_.OnCanWrite();
2478   EXPECT_FALSE(session_.WillingAndAbleToWrite());
2479 }
2480 
TEST_P(QuicSessionTestServer,DonotRetransmitDataOfClosedStreams)2481 TEST_P(QuicSessionTestServer, DonotRetransmitDataOfClosedStreams) {
2482   CompleteHandshake();
2483   InSequence s;
2484 
2485   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2486   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
2487   TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
2488 
2489   QuicStreamFrame frame1(stream2->id(), false, 0, 9);
2490   QuicStreamFrame frame2(stream4->id(), false, 0, 9);
2491   QuicStreamFrame frame3(stream6->id(), false, 0, 9);
2492 
2493   EXPECT_CALL(*stream6, HasPendingRetransmission()).WillOnce(Return(true));
2494   EXPECT_CALL(*stream4, HasPendingRetransmission()).WillOnce(Return(true));
2495   EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(true));
2496   session_.OnFrameLost(QuicFrame(frame3));
2497   session_.OnFrameLost(QuicFrame(frame2));
2498   session_.OnFrameLost(QuicFrame(frame1));
2499 
2500   session_.MarkConnectionLevelWriteBlocked(stream2->id());
2501   session_.MarkConnectionLevelWriteBlocked(stream4->id());
2502   session_.MarkConnectionLevelWriteBlocked(stream6->id());
2503 
2504   // Reset stream 4 locally.
2505   EXPECT_CALL(*connection_, SendControlFrame(_));
2506   EXPECT_CALL(*connection_, OnStreamReset(stream4->id(), _));
2507   stream4->Reset(QUIC_STREAM_CANCELLED);
2508 
2509   // Verify stream 4 is removed from streams with lost data list.
2510   EXPECT_CALL(*stream6, OnCanWrite());
2511   EXPECT_CALL(*stream6, HasPendingRetransmission()).WillOnce(Return(false));
2512   EXPECT_CALL(*stream2, OnCanWrite());
2513   EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(false));
2514   EXPECT_CALL(*connection_, SendControlFrame(_))
2515       .WillRepeatedly(Invoke(&ClearControlFrame));
2516   EXPECT_CALL(*stream2, OnCanWrite());
2517   EXPECT_CALL(*stream6, OnCanWrite());
2518   session_.OnCanWrite();
2519 }
2520 
TEST_P(QuicSessionTestServer,RetransmitFrames)2521 TEST_P(QuicSessionTestServer, RetransmitFrames) {
2522   CompleteHandshake();
2523   MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
2524   QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
2525   InSequence s;
2526 
2527   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2528   TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
2529   TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
2530   EXPECT_CALL(*connection_, SendControlFrame(_))
2531       .WillOnce(Invoke(&ClearControlFrame));
2532   session_.SendWindowUpdate(stream2->id(), 9);
2533 
2534   QuicStreamFrame frame1(stream2->id(), false, 0, 9);
2535   QuicStreamFrame frame2(stream4->id(), false, 0, 9);
2536   QuicStreamFrame frame3(stream6->id(), false, 0, 9);
2537   QuicWindowUpdateFrame window_update(1, stream2->id(), 9);
2538   QuicFrames frames;
2539   frames.push_back(QuicFrame(frame1));
2540   frames.push_back(QuicFrame(&window_update));
2541   frames.push_back(QuicFrame(frame2));
2542   frames.push_back(QuicFrame(frame3));
2543   EXPECT_FALSE(session_.WillingAndAbleToWrite());
2544 
2545   EXPECT_CALL(*stream2, RetransmitStreamData(_, _, _, _))
2546       .WillOnce(Return(true));
2547   EXPECT_CALL(*connection_, SendControlFrame(_))
2548       .WillOnce(Invoke(&ClearControlFrame));
2549   EXPECT_CALL(*stream4, RetransmitStreamData(_, _, _, _))
2550       .WillOnce(Return(true));
2551   EXPECT_CALL(*stream6, RetransmitStreamData(_, _, _, _))
2552       .WillOnce(Return(true));
2553   EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
2554   session_.RetransmitFrames(frames, TLP_RETRANSMISSION);
2555 }
2556 
2557 // Regression test of b/110082001.
TEST_P(QuicSessionTestServer,RetransmitLostDataCausesConnectionClose)2558 TEST_P(QuicSessionTestServer, RetransmitLostDataCausesConnectionClose) {
2559   CompleteHandshake();
2560   // This test mimics the scenario when a dynamic stream retransmits lost data
2561   // and causes connection close.
2562   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
2563   QuicStreamFrame frame(stream->id(), false, 0, 9);
2564 
2565   EXPECT_CALL(*stream, HasPendingRetransmission())
2566       .Times(2)
2567       .WillOnce(Return(true))
2568       .WillOnce(Return(false));
2569   session_.OnFrameLost(QuicFrame(frame));
2570   // Retransmit stream data causes connection close. Stream has not sent fin
2571   // yet, so an RST is sent.
2572   EXPECT_CALL(*stream, OnCanWrite()).WillOnce(Invoke([this, stream]() {
2573     session_.ResetStream(stream->id(), QUIC_STREAM_CANCELLED);
2574   }));
2575   if (VersionHasIetfQuicFrames(transport_version())) {
2576     // Once for the RST_STREAM, once for the STOP_SENDING
2577     EXPECT_CALL(*connection_, SendControlFrame(_))
2578         .Times(2)
2579         .WillRepeatedly(Invoke(&session_, &TestSession::SaveFrame));
2580   } else {
2581     // Just for the RST_STREAM
2582     EXPECT_CALL(*connection_, SendControlFrame(_))
2583         .WillOnce(Invoke(&session_, &TestSession::SaveFrame));
2584   }
2585   EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
2586   session_.OnCanWrite();
2587 }
2588 
TEST_P(QuicSessionTestServer,SendMessage)2589 TEST_P(QuicSessionTestServer, SendMessage) {
2590   // Cannot send message when encryption is not established.
2591   EXPECT_FALSE(session_.OneRttKeysAvailable());
2592   quic::QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
2593   EXPECT_EQ(MessageResult(MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED, 0),
2594             session_.SendMessage(
2595                 MakeSpan(connection_->helper()->GetStreamSendBufferAllocator(),
2596                          "", &storage)));
2597 
2598   CompleteHandshake();
2599   EXPECT_TRUE(session_.OneRttKeysAvailable());
2600 
2601   absl::string_view message;
2602   EXPECT_CALL(*connection_, SendMessage(1, _, false))
2603       .WillOnce(Return(MESSAGE_STATUS_SUCCESS));
2604   EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, 1),
2605             session_.SendMessage(
2606                 MakeSpan(connection_->helper()->GetStreamSendBufferAllocator(),
2607                          message, &storage)));
2608   // Verify message_id increases.
2609   EXPECT_CALL(*connection_, SendMessage(2, _, false))
2610       .WillOnce(Return(MESSAGE_STATUS_TOO_LARGE));
2611   EXPECT_EQ(MessageResult(MESSAGE_STATUS_TOO_LARGE, 0),
2612             session_.SendMessage(
2613                 MakeSpan(connection_->helper()->GetStreamSendBufferAllocator(),
2614                          message, &storage)));
2615   // Verify unsent message does not consume a message_id.
2616   EXPECT_CALL(*connection_, SendMessage(2, _, false))
2617       .WillOnce(Return(MESSAGE_STATUS_SUCCESS));
2618   EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, 2),
2619             session_.SendMessage(
2620                 MakeSpan(connection_->helper()->GetStreamSendBufferAllocator(),
2621                          message, &storage)));
2622 
2623   QuicMessageFrame frame(1);
2624   QuicMessageFrame frame2(2);
2625   EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame)));
2626   EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame2)));
2627 
2628   // Lost message 2.
2629   session_.OnMessageLost(2);
2630   EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame2)));
2631 
2632   // message 1 gets acked.
2633   session_.OnMessageAcked(1, QuicTime::Zero());
2634   EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame)));
2635 }
2636 
2637 // Regression test of b/115323618.
TEST_P(QuicSessionTestServer,LocallyResetZombieStreams)2638 TEST_P(QuicSessionTestServer, LocallyResetZombieStreams) {
2639   CompleteHandshake();
2640   session_.set_writev_consumes_all_data(true);
2641   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2642   std::string body(100, '.');
2643   QuicStreamPeer::CloseReadSide(stream2);
2644   stream2->WriteOrBufferData(body, true, nullptr);
2645   EXPECT_TRUE(stream2->IsWaitingForAcks());
2646   // Verify stream2 is a zombie streams.
2647   ASSERT_TRUE(QuicContainsKey(session_.stream_map(), stream2->id()));
2648   auto* stream = session_.stream_map().find(stream2->id())->second.get();
2649   EXPECT_TRUE(stream->IsZombie());
2650 
2651   QuicStreamFrame frame(stream2->id(), true, 0, 100);
2652   EXPECT_CALL(*stream2, HasPendingRetransmission())
2653       .WillRepeatedly(Return(true));
2654   session_.OnFrameLost(QuicFrame(frame));
2655 
2656   // Reset stream2 locally.
2657   EXPECT_CALL(*connection_, SendControlFrame(_))
2658       .WillRepeatedly(Invoke(&ClearControlFrame));
2659   EXPECT_CALL(*connection_, OnStreamReset(stream2->id(), _));
2660   stream2->Reset(QUIC_STREAM_CANCELLED);
2661 
2662   // Verify stream 2 gets closed.
2663   EXPECT_TRUE(session_.IsClosedStream(stream2->id()));
2664   EXPECT_CALL(*stream2, OnCanWrite()).Times(0);
2665   session_.OnCanWrite();
2666 }
2667 
TEST_P(QuicSessionTestServer,CleanUpClosedStreamsAlarm)2668 TEST_P(QuicSessionTestServer, CleanUpClosedStreamsAlarm) {
2669   CompleteHandshake();
2670   EXPECT_FALSE(
2671       QuicSessionPeer::GetCleanUpClosedStreamsAlarm(&session_)->IsSet());
2672 
2673   session_.set_writev_consumes_all_data(true);
2674   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2675   EXPECT_FALSE(stream2->IsWaitingForAcks());
2676 
2677   CloseStream(stream2->id());
2678   EXPECT_EQ(1u, session_.closed_streams()->size());
2679   EXPECT_TRUE(
2680       QuicSessionPeer::GetCleanUpClosedStreamsAlarm(&session_)->IsSet());
2681 
2682   alarm_factory_.FireAlarm(
2683       QuicSessionPeer::GetCleanUpClosedStreamsAlarm(&session_));
2684   EXPECT_TRUE(session_.closed_streams()->empty());
2685 }
2686 
TEST_P(QuicSessionTestServer,WriteUnidirectionalStream)2687 TEST_P(QuicSessionTestServer, WriteUnidirectionalStream) {
2688   session_.set_writev_consumes_all_data(true);
2689   TestStream* stream4 = new TestStream(GetNthServerInitiatedUnidirectionalId(1),
2690                                        &session_, WRITE_UNIDIRECTIONAL);
2691   session_.ActivateStream(QuicWrapUnique(stream4));
2692   std::string body(100, '.');
2693   stream4->WriteOrBufferData(body, false, nullptr);
2694   stream4->WriteOrBufferData(body, true, nullptr);
2695   ASSERT_TRUE(QuicContainsKey(session_.stream_map(), stream4->id()));
2696   auto* stream = session_.stream_map().find(stream4->id())->second.get();
2697   EXPECT_TRUE(stream->IsZombie());
2698 }
2699 
TEST_P(QuicSessionTestServer,ReceivedDataOnWriteUnidirectionalStream)2700 TEST_P(QuicSessionTestServer, ReceivedDataOnWriteUnidirectionalStream) {
2701   TestStream* stream4 = new TestStream(GetNthServerInitiatedUnidirectionalId(1),
2702                                        &session_, WRITE_UNIDIRECTIONAL);
2703   session_.ActivateStream(QuicWrapUnique(stream4));
2704 
2705   EXPECT_CALL(
2706       *connection_,
2707       CloseConnection(QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM, _, _))
2708       .Times(1);
2709   QuicStreamFrame stream_frame(GetNthServerInitiatedUnidirectionalId(1), false,
2710                                0, 2);
2711   session_.OnStreamFrame(stream_frame);
2712 }
2713 
TEST_P(QuicSessionTestServer,ReadUnidirectionalStream)2714 TEST_P(QuicSessionTestServer, ReadUnidirectionalStream) {
2715   TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1),
2716                                        &session_, READ_UNIDIRECTIONAL);
2717   session_.ActivateStream(QuicWrapUnique(stream4));
2718   EXPECT_FALSE(stream4->IsWaitingForAcks());
2719   // Discard all incoming data.
2720   stream4->StopReading();
2721 
2722   std::string data(100, '.');
2723   QuicStreamFrame stream_frame(GetNthClientInitiatedUnidirectionalId(1), false,
2724                                0, data);
2725   stream4->OnStreamFrame(stream_frame);
2726   EXPECT_TRUE(session_.closed_streams()->empty());
2727 
2728   QuicStreamFrame stream_frame2(GetNthClientInitiatedUnidirectionalId(1), true,
2729                                 100, data);
2730   stream4->OnStreamFrame(stream_frame2);
2731   EXPECT_EQ(1u, session_.closed_streams()->size());
2732 }
2733 
TEST_P(QuicSessionTestServer,WriteOrBufferDataOnReadUnidirectionalStream)2734 TEST_P(QuicSessionTestServer, WriteOrBufferDataOnReadUnidirectionalStream) {
2735   TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1),
2736                                        &session_, READ_UNIDIRECTIONAL);
2737   session_.ActivateStream(QuicWrapUnique(stream4));
2738 
2739   EXPECT_CALL(*connection_,
2740               CloseConnection(
2741                   QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM, _, _))
2742       .Times(1);
2743   std::string body(100, '.');
2744   stream4->WriteOrBufferData(body, false, nullptr);
2745 }
2746 
TEST_P(QuicSessionTestServer,WritevDataOnReadUnidirectionalStream)2747 TEST_P(QuicSessionTestServer, WritevDataOnReadUnidirectionalStream) {
2748   TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1),
2749                                        &session_, READ_UNIDIRECTIONAL);
2750   session_.ActivateStream(QuicWrapUnique(stream4));
2751 
2752   EXPECT_CALL(*connection_,
2753               CloseConnection(
2754                   QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM, _, _))
2755       .Times(1);
2756   std::string body(100, '.');
2757   struct iovec iov = {const_cast<char*>(body.data()), body.length()};
2758   QuicMemSliceStorage storage(
2759       &iov, 1, session_.connection()->helper()->GetStreamSendBufferAllocator(),
2760       1024);
2761   stream4->WriteMemSlices(storage.ToSpan(), false);
2762 }
2763 
TEST_P(QuicSessionTestServer,WriteMemSlicesOnReadUnidirectionalStream)2764 TEST_P(QuicSessionTestServer, WriteMemSlicesOnReadUnidirectionalStream) {
2765   TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1),
2766                                        &session_, READ_UNIDIRECTIONAL);
2767   session_.ActivateStream(QuicWrapUnique(stream4));
2768 
2769   EXPECT_CALL(*connection_,
2770               CloseConnection(
2771                   QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM, _, _))
2772       .Times(1);
2773   char data[1024];
2774   std::vector<std::pair<char*, size_t>> buffers;
2775   buffers.push_back(std::make_pair(data, ABSL_ARRAYSIZE(data)));
2776   buffers.push_back(std::make_pair(data, ABSL_ARRAYSIZE(data)));
2777   QuicTestMemSliceVector vector(buffers);
2778   stream4->WriteMemSlices(vector.span(), false);
2779 }
2780 
2781 // Test code that tests that an incoming stream frame with a new (not previously
2782 // seen) stream id is acceptable. The ID must not be larger than has been
2783 // advertised. It may be equal to what has been advertised.  These tests
2784 // invoke QuicStreamIdManager::MaybeIncreaseLargestPeerStreamId by calling
2785 // QuicSession::OnStreamFrame in order to check that all the steps are connected
2786 // properly and that nothing in the call path interferes with the check.
2787 // First test make sure that streams with ids below the limit are accepted.
TEST_P(QuicSessionTestServer,NewStreamIdBelowLimit)2788 TEST_P(QuicSessionTestServer, NewStreamIdBelowLimit) {
2789   if (!VersionHasIetfQuicFrames(transport_version())) {
2790     // Applicable only to IETF QUIC
2791     return;
2792   }
2793   QuicStreamId bidirectional_stream_id = StreamCountToId(
2794       QuicSessionPeer::ietf_streamid_manager(&session_)
2795               ->advertised_max_incoming_bidirectional_streams() -
2796           1,
2797       Perspective::IS_CLIENT,
2798       /*bidirectional=*/true);
2799 
2800   QuicStreamFrame bidirectional_stream_frame(bidirectional_stream_id, false, 0,
2801                                              "Random String");
2802   EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2803   session_.OnStreamFrame(bidirectional_stream_frame);
2804 
2805   QuicStreamId unidirectional_stream_id = StreamCountToId(
2806       QuicSessionPeer::ietf_streamid_manager(&session_)
2807               ->advertised_max_incoming_unidirectional_streams() -
2808           1,
2809       Perspective::IS_CLIENT,
2810       /*bidirectional=*/false);
2811   QuicStreamFrame unidirectional_stream_frame(unidirectional_stream_id, false,
2812                                               0, "Random String");
2813   EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2814   session_.OnStreamFrame(unidirectional_stream_frame);
2815 }
2816 
2817 // Accept a stream with an ID that equals the limit.
TEST_P(QuicSessionTestServer,NewStreamIdAtLimit)2818 TEST_P(QuicSessionTestServer, NewStreamIdAtLimit) {
2819   if (!VersionHasIetfQuicFrames(transport_version())) {
2820     // Applicable only to IETF QUIC
2821     return;
2822   }
2823   QuicStreamId bidirectional_stream_id =
2824       StreamCountToId(QuicSessionPeer::ietf_streamid_manager(&session_)
2825                           ->advertised_max_incoming_bidirectional_streams(),
2826                       Perspective::IS_CLIENT, /*bidirectional=*/true);
2827   QuicStreamFrame bidirectional_stream_frame(bidirectional_stream_id, false, 0,
2828                                              "Random String");
2829   EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2830   session_.OnStreamFrame(bidirectional_stream_frame);
2831 
2832   QuicStreamId unidirectional_stream_id =
2833       StreamCountToId(QuicSessionPeer::ietf_streamid_manager(&session_)
2834                           ->advertised_max_incoming_unidirectional_streams(),
2835                       Perspective::IS_CLIENT, /*bidirectional=*/false);
2836   QuicStreamFrame unidirectional_stream_frame(unidirectional_stream_id, false,
2837                                               0, "Random String");
2838   EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2839   session_.OnStreamFrame(unidirectional_stream_frame);
2840 }
2841 
2842 // Close the connection if the id exceeds the limit.
TEST_P(QuicSessionTestServer,NewStreamIdAboveLimit)2843 TEST_P(QuicSessionTestServer, NewStreamIdAboveLimit) {
2844   if (!VersionHasIetfQuicFrames(transport_version())) {
2845     // Applicable only to IETF QUIC
2846     return;
2847   }
2848 
2849   QuicStreamId bidirectional_stream_id = StreamCountToId(
2850       QuicSessionPeer::ietf_streamid_manager(&session_)
2851               ->advertised_max_incoming_bidirectional_streams() +
2852           1,
2853       Perspective::IS_CLIENT, /*bidirectional=*/true);
2854   QuicStreamFrame bidirectional_stream_frame(bidirectional_stream_id, false, 0,
2855                                              "Random String");
2856   EXPECT_CALL(
2857       *connection_,
2858       CloseConnection(QUIC_INVALID_STREAM_ID,
2859                       "Stream id 400 would exceed stream count limit 100", _));
2860   session_.OnStreamFrame(bidirectional_stream_frame);
2861 
2862   QuicStreamId unidirectional_stream_id = StreamCountToId(
2863       QuicSessionPeer::ietf_streamid_manager(&session_)
2864               ->advertised_max_incoming_unidirectional_streams() +
2865           1,
2866       Perspective::IS_CLIENT, /*bidirectional=*/false);
2867   QuicStreamFrame unidirectional_stream_frame(unidirectional_stream_id, false,
2868                                               0, "Random String");
2869   EXPECT_CALL(
2870       *connection_,
2871       CloseConnection(QUIC_INVALID_STREAM_ID,
2872                       "Stream id 402 would exceed stream count limit 100", _));
2873   session_.OnStreamFrame(unidirectional_stream_frame);
2874 }
2875 
2876 // Checks that invalid stream ids are handled.
TEST_P(QuicSessionTestServer,OnStopSendingInvalidStreamId)2877 TEST_P(QuicSessionTestServer, OnStopSendingInvalidStreamId) {
2878   if (!VersionHasIetfQuicFrames(transport_version())) {
2879     return;
2880   }
2881   // Check that "invalid" stream ids are rejected.
2882   QuicStopSendingFrame frame(1, -1, QUIC_STREAM_CANCELLED);
2883   EXPECT_CALL(
2884       *connection_,
2885       CloseConnection(QUIC_INVALID_STREAM_ID,
2886                       "Received STOP_SENDING for an invalid stream", _));
2887   session_.OnStopSendingFrame(frame);
2888 }
2889 
TEST_P(QuicSessionTestServer,OnStopSendingReadUnidirectional)2890 TEST_P(QuicSessionTestServer, OnStopSendingReadUnidirectional) {
2891   if (!VersionHasIetfQuicFrames(transport_version())) {
2892     return;
2893   }
2894   // It's illegal to send STOP_SENDING with a stream ID that is read-only.
2895   QuicStopSendingFrame frame(1, GetNthClientInitiatedUnidirectionalId(1),
2896                              QUIC_STREAM_CANCELLED);
2897   EXPECT_CALL(
2898       *connection_,
2899       CloseConnection(QUIC_INVALID_STREAM_ID,
2900                       "Received STOP_SENDING for a read-only stream", _));
2901   session_.OnStopSendingFrame(frame);
2902 }
2903 
2904 // Static streams ignore STOP_SENDING.
TEST_P(QuicSessionTestServer,OnStopSendingStaticStreams)2905 TEST_P(QuicSessionTestServer, OnStopSendingStaticStreams) {
2906   if (!VersionHasIetfQuicFrames(transport_version())) {
2907     return;
2908   }
2909   QuicStreamId stream_id = 0;
2910   std::unique_ptr<TestStream> fake_static_stream = std::make_unique<TestStream>(
2911       stream_id, &session_, /*is_static*/ true, BIDIRECTIONAL);
2912   QuicSessionPeer::ActivateStream(&session_, std::move(fake_static_stream));
2913   // Check that a stream id in the static stream map is ignored.
2914   QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED);
2915   EXPECT_CALL(*connection_,
2916               CloseConnection(QUIC_INVALID_STREAM_ID,
2917                               "Received STOP_SENDING for a static stream", _));
2918   session_.OnStopSendingFrame(frame);
2919 }
2920 
2921 // If stream is write closed, do not send a RESET_STREAM frame.
TEST_P(QuicSessionTestServer,OnStopSendingForWriteClosedStream)2922 TEST_P(QuicSessionTestServer, OnStopSendingForWriteClosedStream) {
2923   if (!VersionHasIetfQuicFrames(transport_version())) {
2924     return;
2925   }
2926 
2927   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
2928   QuicStreamId stream_id = stream->id();
2929   QuicStreamPeer::SetFinSent(stream);
2930   stream->CloseWriteSide();
2931   EXPECT_TRUE(stream->write_side_closed());
2932   QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED);
2933   EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2934   session_.OnStopSendingFrame(frame);
2935 }
2936 
2937 // If stream is closed, return true and do not close the connection.
TEST_P(QuicSessionTestServer,OnStopSendingClosedStream)2938 TEST_P(QuicSessionTestServer, OnStopSendingClosedStream) {
2939   if (!VersionHasIetfQuicFrames(transport_version())) {
2940     return;
2941   }
2942   CompleteHandshake();
2943   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
2944   QuicStreamId stream_id = stream->id();
2945   CloseStream(stream_id);
2946   QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED);
2947   EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2948   session_.OnStopSendingFrame(frame);
2949 }
2950 
2951 // If stream id is a nonexistent local stream, return false and close the
2952 // connection.
TEST_P(QuicSessionTestServer,OnStopSendingInputNonExistentLocalStream)2953 TEST_P(QuicSessionTestServer, OnStopSendingInputNonExistentLocalStream) {
2954   if (!VersionHasIetfQuicFrames(transport_version())) {
2955     return;
2956   }
2957 
2958   QuicStopSendingFrame frame(1, GetNthServerInitiatedBidirectionalId(123456),
2959                              QUIC_STREAM_CANCELLED);
2960   EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_STREAM_WRONG_DIRECTION,
2961                                             "Data for nonexistent stream", _))
2962       .Times(1);
2963   session_.OnStopSendingFrame(frame);
2964 }
2965 
2966 // If a STOP_SENDING is received for a peer initiated stream, the new stream
2967 // will be created.
TEST_P(QuicSessionTestServer,OnStopSendingNewStream)2968 TEST_P(QuicSessionTestServer, OnStopSendingNewStream) {
2969   CompleteHandshake();
2970   if (!VersionHasIetfQuicFrames(transport_version())) {
2971     return;
2972   }
2973   QuicStopSendingFrame frame(1, GetNthClientInitiatedBidirectionalId(1),
2974                              QUIC_STREAM_CANCELLED);
2975 
2976   // A Rst will be sent as a response for STOP_SENDING.
2977   EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1);
2978   EXPECT_CALL(*connection_, OnStreamReset(_, _)).Times(1);
2979   session_.OnStopSendingFrame(frame);
2980 
2981   QuicStream* stream =
2982       session_.GetOrCreateStream(GetNthClientInitiatedBidirectionalId(1));
2983   EXPECT_TRUE(stream);
2984   EXPECT_TRUE(stream->write_side_closed());
2985 }
2986 
2987 // For a valid stream, ensure that all works
TEST_P(QuicSessionTestServer,OnStopSendingInputValidStream)2988 TEST_P(QuicSessionTestServer, OnStopSendingInputValidStream) {
2989   CompleteHandshake();
2990   if (!VersionHasIetfQuicFrames(transport_version())) {
2991     // Applicable only to IETF QUIC
2992     return;
2993   }
2994 
2995   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
2996 
2997   // Ensure that the stream starts out open in both directions.
2998   EXPECT_FALSE(stream->write_side_closed());
2999   EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream));
3000 
3001   QuicStreamId stream_id = stream->id();
3002   QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED);
3003   // Expect a reset to come back out.
3004   EXPECT_CALL(*connection_, SendControlFrame(_));
3005   EXPECT_CALL(*connection_, OnStreamReset(stream_id, QUIC_STREAM_CANCELLED));
3006   EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
3007   session_.OnStopSendingFrame(frame);
3008 
3009   EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream));
3010   EXPECT_TRUE(stream->write_side_closed());
3011 }
3012 
TEST_P(QuicSessionTestServer,WriteBufferedCryptoFrames)3013 TEST_P(QuicSessionTestServer, WriteBufferedCryptoFrames) {
3014   if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
3015     return;
3016   }
3017   std::string data(1350, 'a');
3018   TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
3019   // Only consumed 1000 bytes.
3020   EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0))
3021       .WillOnce(Return(1000));
3022   crypto_stream->WriteCryptoData(ENCRYPTION_INITIAL, data);
3023   EXPECT_TRUE(session_.HasPendingHandshake());
3024   EXPECT_TRUE(session_.WillingAndAbleToWrite());
3025 
3026   EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0);
3027   connection_->SetEncrypter(
3028       ENCRYPTION_ZERO_RTT,
3029       std::make_unique<NullEncrypter>(connection_->perspective()));
3030   crypto_stream->WriteCryptoData(ENCRYPTION_ZERO_RTT, data);
3031 
3032   EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 350, 1000))
3033       .WillOnce(Return(350));
3034   EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0))
3035       .WillOnce(Return(1350));
3036   session_.OnCanWrite();
3037   EXPECT_FALSE(session_.HasPendingHandshake());
3038   EXPECT_FALSE(session_.WillingAndAbleToWrite());
3039 }
3040 
3041 // Regression test for
3042 // https://bugs.chromium.org/p/chromium/issues/detail?id=1002119
TEST_P(QuicSessionTestServer,StreamFrameReceivedAfterFin)3043 TEST_P(QuicSessionTestServer, StreamFrameReceivedAfterFin) {
3044   TestStream* stream = session_.CreateOutgoingBidirectionalStream();
3045   QuicStreamFrame frame(stream->id(), true, 0, ",");
3046   session_.OnStreamFrame(frame);
3047 
3048   QuicStreamFrame frame1(stream->id(), false, 1, ",");
3049   EXPECT_CALL(*connection_,
3050               CloseConnection(QUIC_STREAM_DATA_BEYOND_CLOSE_OFFSET, _, _));
3051   session_.OnStreamFrame(frame1);
3052 }
3053 
TEST_P(QuicSessionTestServer,ResetForIETFStreamTypes)3054 TEST_P(QuicSessionTestServer, ResetForIETFStreamTypes) {
3055   CompleteHandshake();
3056   if (!VersionHasIetfQuicFrames(transport_version())) {
3057     return;
3058   }
3059 
3060   QuicStreamId read_only = GetNthClientInitiatedUnidirectionalId(0);
3061 
3062   EXPECT_CALL(*connection_, SendControlFrame(_))
3063       .Times(1)
3064       .WillOnce(Invoke(&ClearControlFrame));
3065   EXPECT_CALL(*connection_, OnStreamReset(read_only, _));
3066   session_.ResetStream(read_only, QUIC_STREAM_CANCELLED);
3067 
3068   QuicStreamId write_only = GetNthServerInitiatedUnidirectionalId(0);
3069   EXPECT_CALL(*connection_, SendControlFrame(_))
3070       .Times(1)
3071       .WillOnce(Invoke(&ClearControlFrame));
3072   EXPECT_CALL(*connection_, OnStreamReset(write_only, _));
3073   session_.ResetStream(write_only, QUIC_STREAM_CANCELLED);
3074 
3075   QuicStreamId bidirectional = GetNthClientInitiatedBidirectionalId(0);
3076   EXPECT_CALL(*connection_, SendControlFrame(_))
3077       .Times(2)
3078       .WillRepeatedly(Invoke(&ClearControlFrame));
3079   EXPECT_CALL(*connection_, OnStreamReset(bidirectional, _));
3080   session_.ResetStream(bidirectional, QUIC_STREAM_CANCELLED);
3081 }
3082 
TEST_P(QuicSessionTestServer,DecryptionKeyAvailableBeforeEncryptionKey)3083 TEST_P(QuicSessionTestServer, DecryptionKeyAvailableBeforeEncryptionKey) {
3084   if (connection_->version().handshake_protocol != PROTOCOL_TLS1_3) {
3085     return;
3086   }
3087   ASSERT_FALSE(connection_->framer().HasEncrypterOfEncryptionLevel(
3088       ENCRYPTION_HANDSHAKE));
3089   EXPECT_FALSE(session_.OnNewDecryptionKeyAvailable(
3090       ENCRYPTION_HANDSHAKE, /*decrypter=*/nullptr,
3091       /*set_alternative_decrypter=*/false, /*latch_once_used=*/false));
3092 }
3093 
TEST_P(QuicSessionTestServer,IncomingStreamWithServerInitiatedStreamId)3094 TEST_P(QuicSessionTestServer, IncomingStreamWithServerInitiatedStreamId) {
3095   const QuicErrorCode expected_error =
3096       VersionHasIetfQuicFrames(transport_version())
3097           ? QUIC_HTTP_STREAM_WRONG_DIRECTION
3098           : QUIC_INVALID_STREAM_ID;
3099   EXPECT_CALL(
3100       *connection_,
3101       CloseConnection(expected_error, "Data for nonexistent stream",
3102                       ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
3103 
3104   QuicStreamFrame frame(GetNthServerInitiatedBidirectionalId(1),
3105                         /* fin = */ false, /* offset = */ 0,
3106                         absl::string_view("foo"));
3107   session_.OnStreamFrame(frame);
3108 }
3109 
3110 // A client test class that can be used when the automatic configuration is not
3111 // desired.
3112 class QuicSessionTestClientUnconfigured : public QuicSessionTestBase {
3113  protected:
QuicSessionTestClientUnconfigured()3114   QuicSessionTestClientUnconfigured()
3115       : QuicSessionTestBase(Perspective::IS_CLIENT,
3116                             /*configure_session=*/false) {}
3117 };
3118 
3119 INSTANTIATE_TEST_SUITE_P(Tests,
3120                          QuicSessionTestClientUnconfigured,
3121                          ::testing::ValuesIn(AllSupportedVersions()),
3122                          ::testing::PrintToStringParamName());
3123 
TEST_P(QuicSessionTestClientUnconfigured,StreamInitiallyBlockedThenUnblocked)3124 TEST_P(QuicSessionTestClientUnconfigured, StreamInitiallyBlockedThenUnblocked) {
3125   if (!connection_->version().AllowsLowFlowControlLimits()) {
3126     return;
3127   }
3128   // Create a stream before negotiating the config and verify it starts off
3129   // blocked.
3130   QuicSessionPeer::SetMaxOpenOutgoingBidirectionalStreams(&session_, 10);
3131   TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
3132   EXPECT_TRUE(stream2->IsFlowControlBlocked());
3133   EXPECT_TRUE(session_.IsConnectionFlowControlBlocked());
3134   EXPECT_TRUE(session_.IsStreamFlowControlBlocked());
3135 
3136   // Negotiate the config with higher received limits.
3137   QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional(
3138       session_.config(), kMinimumFlowControlSendWindow);
3139   QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(
3140       session_.config(), kMinimumFlowControlSendWindow);
3141   session_.OnConfigNegotiated();
3142 
3143   // Stream is now unblocked.
3144   EXPECT_FALSE(stream2->IsFlowControlBlocked());
3145   EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
3146   EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
3147 }
3148 
3149 }  // namespace
3150 }  // namespace test
3151 }  // namespace quic
3152